import React, { useState, useContext } from "react";
import { GlobalContext, showToast } from "Src/globalContext";
import { uploadFilesDataAPI } from "Src/services/workOrderService";
import WorkOrderUploadedDemo from "./WorkOrderUploadedDemo";
import WorkOrderEmptyDemo from "./WorkOrderEmptyDemo";
import WorkOrderUploadedMaster from "./WorkOrderUploadedMaster";
import WorkOrderEmptyMaster from "./WorkOrderEmptyMaster";
import WorkOrderLyrics from "./WorkOrderLyrics";
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
import IdeasNotesModal from "Components/ideaNotes";
import { useS3Upload } from "Src/libs/uploads3Hook";
import { useS3UploadMaster } from "Src/libs/uploads3HookMaster";

const WorkOrderSubProject = ({
  subProject,
  workOrderDetails,
  uploadedDemoFiles,
  uploadedMasterFiles,
  setLyrics,
}) => {
  const {
    dispatch: globalDispatch,
    state: { subproject_update },
  } = useContext(GlobalContext);
  const [activeTab, setActiveTab] = useState("demo");
  const [showIdeasNotesModal, setShowIdeasNotesModal] = React.useState(false);
  const { uploadS3FilesAPI, progress, error, isUploading } = useS3Upload();
  const [employeeType, setEmployeeType] = useState("");
  const {
    uploadS3FilesAPI: uploadS3FilesMasterAPI,
    progress: progressMaster,
    error: errorMaster,
    isUploading: isUploadingMaster,
  } = useS3UploadMaster();
  const [fileType, setFileType] = useState("");
  const [employeeId, setEmployeeId] = useState(null);

  const handleUpdateLyrics = (lyrics) => {
    setLyrics({
      subproject_id: subProject.id,
      lyrics: lyrics,
    });
  };

  const handleEmployeeType = (employeeType) => {
    setEmployeeType(employeeType);
    if (employeeType === "engineer") {
      setEmployeeId(Number(workOrderDetails.engineer_id));
    }
  };

  const handleUploadFileType = (fileType) => {
    setFileType(fileType);
  };

  const handleMasterUploads = async (formData) => {
    try {
      // setIsLoading(true);
      const result = await uploadS3FilesMasterAPI(formData);
      if (!result.error) {
        const payload = {
          project_id: subProject.project_id
            ? Number(subProject.project_id)
            : null,
          subproject_id: subProject.id ? Number(subProject.id) : null,
          workorder_id: Number(subProject.workorder_id),
          employee_id: employeeId,
          employee_type: employeeType,
          type: fileType,
          attachments: result.attachments,
        };

        const fileUploadDataResult = await uploadFilesDataAPI(payload);
        if (!fileUploadDataResult.error) {
          showToast(globalDispatch, "Files updated successfully", 5000);
          globalDispatch({
            type: "SET_SUBPROJECT_UPDATE",
            payload: !subproject_update,
          });
        } else {
          showToast(
            globalDispatch,
            fileUploadDataResult.message,
            5000,
            "error"
          );
        }
        // setIsLoading(false);
      } else {
        showToast(globalDispatch, result.message, 5000, "error");
        // setIsLoading(false);
      }
    } catch (error) {
      showToast(globalDispatch, error.message, 5000, "error");
    }
  };

  const handleDemoUploads = async (formData) => {
    try {
      // setIsLoading(true);
      const result = await uploadS3FilesAPI(formData);
      if (!result.error) {
        const payload = {
          project_id: subProject.project_id
            ? Number(subProject.project_id)
            : null,
          subproject_id: subProject.id ? Number(subProject.id) : null,
          workorder_id: Number(subProject.workorder_id),
          employee_id: employeeId,
          employee_type: employeeType,
          type: fileType,
          attachments: result.attachments,
        };

        const fileUploadDataResult = await uploadFilesDataAPI(payload);
        if (!fileUploadDataResult.error) {
          showToast(globalDispatch, "Files updated successfully", 5000);
          globalDispatch({
            type: "SET_SUBPROJECT_UPDATE",
            payload: !subproject_update,
          });
        } else {
          showToast(
            globalDispatch,
            fileUploadDataResult.message,
            5000,
            "error"
          );
        }
        // setIsLoading(false);
      } else {
        showToast(globalDispatch, result.message, 5000, "error");
        // setIsLoading(false);
      }
    } catch (error) {
      showToast(globalDispatch, error.message, 5000, "error");
    }
  };

  const handleWriterNotesModalClose = () => {
    setShowIdeasNotesModal(false);
  };

  return (
    <div className="shadow-default rounded border border-stroke bg-boxdark p-5">
      {/* Header Section */}
      <div className="mb-4 flex items-center justify-between border-b border-stroke pb-4">
        <div className="flex flex-col">
          <div className="flex items-center gap-3">
            <h4 className="text-lg font-semibold text-white">
              {subProject.type}: {subProject.program_name}
            </h4>
            <span className="text-sm text-bodydark2">
              - {subProject.team_name}
            </span>
          </div>
          <span className="mt-1 text-sm text-bodydark2">
            Team Type: {subProject.team_type === 1 ? "All Girl" : "Coed"}
          </span>
        </div>

        <FontAwesomeIcon
          className="cursor-pointer text-2xl text-white hover:text-primary"
          icon="fa-solid fa-book"
          onClick={() => setShowIdeasNotesModal(true)}
        />
      </div>

      {/* Tabs Navigation */}
      <div className="mb-6 border-b border-stroke">
        <nav className="-mb-px flex space-x-4">
          <button
            className={`px-4 py-2 text-sm font-medium transition-colors duration-200 ${
              activeTab === "demo"
                ? "border-b-2 border-primary text-primary"
                : "text-bodydark2 hover:text-white"
            }`}
            onClick={() => setActiveTab("demo")}
          >
            Demo Files
          </button>
          <button
            className={`px-4 py-2 text-sm font-medium transition-colors duration-200 ${
              activeTab === "master"
                ? "border-b-2 border-primary text-primary"
                : "text-bodydark2 hover:text-white"
            }`}
            onClick={() => setActiveTab("master")}
          >
            Master Files
          </button>
          <button
            className={`px-4 py-2 text-sm font-medium transition-colors duration-200 ${
              activeTab === "lyrics"
                ? "border-b-2 border-primary text-primary"
                : "text-bodydark2 hover:text-white"
            }`}
            onClick={() => setActiveTab("lyrics")}
          >
            Lyrics
          </button>
        </nav>
      </div>

      {/* Tab Content */}
      <div className="rounded border border-stroke bg-boxdark-2 p-4">
        {activeTab === "demo" && (
          <div>
            {uploadedDemoFiles.length > 0 ? (
              <WorkOrderUploadedDemo
                uploadedFilesProgressData={{ progress, error, isUploading }}
                uploadedFiles={uploadedDemoFiles}
              />
            ) : (
              <WorkOrderEmptyDemo
                uploadedFilesProgressData={{ progress, error, isUploading }}
                setEmployeeType={handleEmployeeType}
                setFileUploadType={handleUploadFileType}
                setFormData={handleDemoUploads}
              />
            )}
          </div>
        )}

        {activeTab === "master" && (
          <div>
            {uploadedMasterFiles.length > 0 ? (
              <WorkOrderUploadedMaster uploadedFiles={uploadedMasterFiles} />
            ) : (
              <WorkOrderEmptyMaster
                setEmployeeType={handleEmployeeType}
                setFileUploadType={handleUploadFileType}
                setFormData={handleMasterUploads}
                uploadedFilesProgressData={{
                  progress: progressMaster,
                  error: errorMaster,
                  isUploading: isUploadingMaster,
                }}
              />
            )}
          </div>
        )}

        {activeTab === "lyrics" && (
          <WorkOrderLyrics
            subProjectId={subProject.id}
            lyrics={subProject.lyrics}
            setLyrics={handleUpdateLyrics}
          />
        )}
      </div>

      {/* Ideas Notes Modal */}
      {showIdeasNotesModal && (
        <IdeasNotesModal
          ideas={subProject.ideas}
          theme={subProject.survey.theme_of_the_routine}
          setModalClose={handleWriterNotesModalClose}
          notes={subProject.notes}
        />
      )}
    </div>
  );
};

export default WorkOrderSubProject;
