import React, { useState, useContext } from "react";
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 Lyrics from "../WriterWorkOrder/Lyrics";

const EngineerSubProject = ({
  isPublic = false,
  canUpload = true,
  workOrderDetails,
  subProject,
  uploadedFiles,
  setDeleteFileId,
}) => {
  const {
    dispatch: globalDispatch,
    state: { subproject_update },
  } = useContext(GlobalContext);
  const [showIdeasNotesModal, setShowIdeasNotesModal] = React.useState(false);
  const [activeTab, setActiveTab] = useState("master");
  const {
    uploadS3FilesAPI: uploadS3FilesMasterAPI,
    progress: progressMaster,
    error: errorMaster,
    isUploading: isUploadingMaster,
  } = useS3UploadMaster();

  const [employeeType, setEmployeeType] = useState("");
  const [fileType, setFileType] = useState("");
  const [employeeId, setEmployeeId] = 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 w-full max-w-5xl 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>
              <span className="ml-2 text-primary">
                - {subProject.team_name}
              </span>
            </h4>
          </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.is_song ? (
          <button
            className={`px-4 py-2 text-sm font-semibold ${
              activeTab === "details"
                ? "border-b-2 border-white text-primary"
                : "text-bodydark hover:text-white"
            }`}
            onClick={() => setActiveTab("details")}
          >
            Song Details
          </button>
        ) : null}
        <button
          className={`px-4 py-2 text-sm font-semibold ${
            activeTab === "lyrics"
              ? "border-b-2 border-white text-primary"
              : "text-bodydark hover:text-white"
          }`}
          onClick={() => setActiveTab("lyrics")}
        >
          Lyrics
        </button>
        {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>
        )}
        <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 === "master" && (
          <div className="min-h-[350px] rounded border border-form-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 === "details" && subProject.is_song && (
          <div className="min-h-[350px] rounded border border-form-strokedark bg-form-input p-4">
            <div className="flex flex-col gap-4">
              <div className="flex items-center gap-4">
                <span className="text-sm font-medium text-white">
                  Song Title:
                </span>
                <span className="text-sm text-bodydark2">
                  {subProject.type_name || "N/A"}
                </span>
              </div>
              <div className="flex items-center gap-4">
                <span className="text-sm font-medium text-white">BPM:</span>
                <span className="text-sm text-bodydark2">
                  {subProject.bpm || "N/A"}
                </span>
              </div>
              <div className="flex items-center gap-4">
                <span className="text-sm font-medium text-white">Key:</span>
                <span className="text-sm text-bodydark2">
                  {subProject.song_key || "N/A"}
                </span>
              </div>
            </div>
          </div>
        )}

        {activeTab === "lyrics" && (
          <div className="min-h-[350px] rounded border border-form-strokedark bg-form-input p-4">
            <Lyrics
              canUpload={canUpload}
              subProjectId={subProject.id}
              lyrics={subProject.lyrics}
              setLyrics={{}}
            />
          </div>
        )}

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

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

export default EngineerSubProject;
