import React from "react";
import { useNavigate } from "react-router";
import { AuthContext } from "Src/authContext";
import { GlobalContext, showToast } from "Src/globalContext";
import {
  uploadS3FilesAPI,
  uploadFilesDataAPI,
} from "Src/services/workOrderService";
import EmptyMaster from "./EmptyMaster";
import UploadedMaster from "./UploadedMaster";
import AdminInstrumentals from "Components/AdminInstrumentals";
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
import IdeasNotesModal from "Components/ideaNotes";
import { useS3UploadMaster } from "Src/libs/uploads3HookMaster";
import { Link } from "react-router-dom";

const EngineerSubProject = ({
  isPublic = false,
  canUpload = true,
  workOrderDetails,
  subProject,
  uploadedFiles,
  setDeleteFileId,
}) => {
  const navigate = useNavigate();

  const { state: authState } = React.useContext(AuthContext);
  const {
    dispatch: globalDispatch,
    state: { subproject_update },
  } = React.useContext(GlobalContext);
  const [showIdeasNotesModal, setShowIdeasNotesModal] = React.useState(false);
  const [activeTab, setActiveTab] = React.useState("master");

  const {
    uploadS3FilesAPI: uploadS3FilesMasterAPI,
    progress: progressMaster,
    error: errorMaster,
    isUploading: isUploadingMaster,
  } = useS3UploadMaster();

  const [employeeType, setEmployeeType] = React.useState("");
  const [fileType, setFileType] = React.useState("");
  const [employeeId, setEmployeeId] = React.useState(null);

  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: Number(workOrderDetails.engineer_id),
          employee_type: "engineer",
          type: "master",
          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-strokedark bg-boxdark p-4">
      {/* Header Section */}
      <div className="mb-4 flex items-center justify-between border-b border-strokedark pb-4">
        <div className="flex flex-col">
          <div className="flex items-center gap-3">
            <h4 className="text-lg font-semibold text-white">
              <span>{subProject.type}:</span>
              <span className="ml-2">{subProject.program_name}</span>
            </h4>
            <Link
              to={`/${authState.role}/view-project/${subProject.project_id}`}
              className="cursor-pointer text-primary hover:underline"
              onClick={() => {
                localStorage.setItem("projectClientId", "");
                localStorage.setItem("projectTeamName", "");
                localStorage.setItem("projectMixTypeId", "");
                localStorage.setItem("projectMixDateStart", "");
                localStorage.setItem("projectMixDateEnd", "");
                localStorage.setItem("projectPageSize", "");
              }}
            >
              {subProject.team_name}
            </Link>
          </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 flex gap-2 border-b border-stroke">
        {subProject.admin_writer_instrumentals?.length > 0 && (
          <button
            className={`px-4 py-2 text-sm font-semibold ${
              activeTab === "instrumentals"
                ? "border-b-2 border-white text-primary"
                : "text-bodydark hover:text-white"
            }`}
            onClick={() => setActiveTab("instrumentals")}
          >
            Instrumentals
          </button>
        )}
        {subProject.is_song ? (
          <button
            className={`px-4 py-2 text-sm font-semibold ${
              activeTab === "song"
                ? "border-b-2 border-white text-primary"
                : "text-bodydark hover:text-white"
            }`}
            onClick={() => setActiveTab("song")}
          >
            Song Details
          </button>
        ) : null}
        <button
          className={`px-4 py-2 text-sm font-semibold ${
            activeTab === "master"
              ? "border-b-2 border-white text-primary"
              : "text-bodydark hover:text-white"
          }`}
          onClick={() => setActiveTab("master")}
        >
          Master Files
        </button>
      </div>

      {/* Tab Content */}
      <div className="mt-4">
        {activeTab === "song" && subProject.is_song && (
          <div className="min-h-[350px] rounded border border-strokedark bg-form-input p-4">
            <div className="flex flex-col gap-4">
              <div className="grid grid-cols-2 gap-4">
                <div className="flex flex-col">
                  <span className="text-sm font-medium text-bodydark2">
                    Song Title
                  </span>
                  <span className="text-base font-semibold text-white">
                    {subProject.type_name || "N/A"}
                  </span>
                </div>
                <div className="flex flex-col">
                  <span className="text-sm font-medium text-bodydark2">
                    BPM
                  </span>
                  <span className="text-base font-semibold text-white">
                    {subProject.bpm || "N/A"}
                  </span>
                </div>
                <div className="flex flex-col">
                  <span className="text-sm font-medium text-bodydark2">
                    Key
                  </span>
                  <span className="text-base font-semibold text-white">
                    {subProject.song_key || "N/A"}
                  </span>
                </div>
              </div>
            </div>
          </div>
        )}

        {activeTab === "master" && (
          <div className="min-h-[350px] rounded border border-strokedark bg-form-input p-4">
            {uploadedFiles.length === 0 ? (
              <EmptyMaster
                canUpload={canUpload}
                setEmployeeType={handleEmployeeType}
                setFileUploadType={handleUploadFileType}
                setFormData={handleMasterUploads}
                uploadedFilesProgressData={{
                  progress: progressMaster,
                  error: errorMaster,
                  isUploading: isUploadingMaster,
                }}
              />
            ) : (
              <UploadedMaster
                canUpload={canUpload}
                uploadedFiles={uploadedFiles}
                setDeleteFileId={setDeleteFileId}
                setEmployeeType={handleEmployeeType}
                setFileUploadType={handleUploadFileType}
                setFormData={handleMasterUploads}
                uploadedFilesProgressData={{
                  progress: progressMaster,
                  error: errorMaster,
                  isUploading: isUploadingMaster,
                }}
              />
            )}
          </div>
        )}

        {activeTab === "instrumentals" && (
          <div className="min-h-[350px] rounded border border-strokedark bg-form-input p-4">
            <AdminInstrumentals
              uploadedFiles={subProject.admin_writer_instrumentals}
            />
          </div>
        )}
      </div>

      {showIdeasNotesModal && (
        <IdeasNotesModal
          theme={subProject.survey.theme_of_the_routine}
          ideas={subProject.ideas}
          setModalClose={() => setShowIdeasNotesModal(false)}
          notes={subProject.notes}
        />
      )}
    </div>
  );
};

export default EngineerSubProject;
