import React from "react";
import { GlobalContext, showToast } from "Src/globalContext";
import { uploadFilesDataAPI } from "Src/services/workOrderService";
import Lyrics from "./Lyrics";
import EmptyDemo from "./EmptyDemo";
import UploadedDemo from "./UploadedDemo";
import AdminInstrumentals from "Components/AdminInstrumentals";
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
import IdeasNotesModal from "Components/ideaNotes";
import { useS3Upload } from "Src/libs/uploads3Hook";

const SubProject = ({
  canUpload = true,
  workOrderDetails,
  subProject,
  uploadedFiles,
  setDeleteFileId,
  setLyrics,
  setSubProjectDetails,
}) => {
  const { dispatch: globalDispatch, state } = React.useContext(GlobalContext);
  const { uploadS3FilesAPI, progress, error, isUploading } = useS3Upload();
  const { songSubProjects, subproject_update } = state;

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

  const [songTitle, setSongTitle] = React.useState(subProject.type);
  const [bpm, setBpm] = React.useState(subProject.bpm);
  const [key, setKey] = React.useState(subProject.song_key);

  const [activeTab, setActiveTab] = React.useState("demos");

  const handleOnChangeTitle = (e) => {
    e.preventDefault();

    const songIndex = songSubProjects.findIndex(
      (song) => song.subproject_id === subProject.id
    );

    if (songIndex > -1) {
      const updatedSongs = [...songSubProjects];
      updatedSongs[songIndex].type_name = e.target.value;
      updatedSongs[songIndex].is_song = 1;
      globalDispatch({
        type: "SET_SONG_SUB_PROJECTS",
        payload: updatedSongs,
      });
    } else {
      globalDispatch({
        type: "SET_SONG_SUB_PROJECTS",
        payload: [
          ...songSubProjects,
          {
            subproject_id: subProject.id,
            type_name: e.target.value,
            is_song: 1,
          },
        ],
      });
    }
  };

  const handleOnChangeBpm = (e) => {
    e.preventDefault();

    const songIndex = songSubProjects.findIndex(
      (song) => song.subproject_id === subProject.id
    );

    if (songIndex > -1) {
      const updatedSongs = [...songSubProjects];
      updatedSongs[songIndex].bpm = e.target.value;
      updatedSongs[songIndex].is_song = 1;
      globalDispatch({
        type: "SET_SONG_SUB_PROJECTS",
        payload: updatedSongs,
      });
    } else {
      globalDispatch({
        type: "SET_SONG_SUB_PROJECTS",
        payload: [
          ...songSubProjects,
          {
            subproject_id: subProject.id,
            bpm: e.target.value,
            is_song: 1,
          },
        ],
      });
    }
  };

  const handleOnChangeKey = (e) => {
    e.preventDefault();

    const songIndex = songSubProjects.findIndex(
      (song) => song.subproject_id === subProject.id
    );

    if (songIndex > -1) {
      const updatedSongs = [...songSubProjects];
      updatedSongs[songIndex].song_key = e.target.value;
      updatedSongs[songIndex].is_song = 1;
      globalDispatch({
        type: "SET_SONG_SUB_PROJECTS",
        payload: updatedSongs,
      });
    } else {
      globalDispatch({
        type: "SET_SONG_SUB_PROJECTS",
        payload: [
          ...songSubProjects,
          {
            subproject_id: subProject.id,
            song_key: e.target.value,
            is_song: 1,
          },
        ],
      });
    }
  };

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

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

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

  const handleSubProjectDetails = (e) => {
    e.preventDefault();
    if (songTitle === "") {
      showToast(globalDispatch, "Please enter song title", 5000, "error");
      return;
    }
    if (bpm === "") {
      showToast(globalDispatch, "Please enter bpm", 5000, "error");
      return;
    }
    if (key === "") {
      showToast(globalDispatch, "Please enter key", 5000, "error");
      return;
    }

    setSubProjectDetails({
      subproject_id: Number(subProject.id),
      type_name: songTitle,
      bpm: bpm,
      song_key: key,
      is_song: 1,
    });
  };

  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: subProject.workorder_id
            ? Number(subProject.workorder_id)
            : null,
          employee_id: Number(workOrderDetails.writer_id),
          employee_type: "writer",
          type: "demo",
          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>
            </h4>
            <span className="text-primary">{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 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 === "demos"
              ? "border-b-2 border-white text-primary"
              : "text-bodydark hover:text-white"
          }`}
          onClick={() => setActiveTab("demos")}
        >
          Demo Files
        </button>
        <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>
        )}
      </div>

      {/* Tab Content */}
      <div className="mt-4">
        {activeTab === "details" && subProject.is_song ? (
          <div className="min-h-[350px] rounded border border-form-strokedark bg-form-input p-4">
            <form className="flex flex-col gap-4">
              <div className="w-full md:w-1/2">
                <label className="mb-2.5 block text-sm font-medium text-white">
                  Song Title
                </label>
                <input
                  type="text"
                  placeholder="Enter Song Title"
                  defaultValue={subProject.type_name}
                  onChange={(e) => {
                    setSongTitle(e.target.value);
                    handleOnChangeTitle(e);
                  }}
                  className="w-full rounded-md border border-form-strokedark bg-form-input px-4 py-2.5 text-white focus:border-white focus:outline-none"
                />
              </div>
              <div className="w-full md:w-1/2">
                <label className="mb-2.5 block text-sm font-medium text-white">
                  BPM
                </label>
                <input
                  type="text"
                  placeholder="Enter BPM"
                  defaultValue={subProject.bpm}
                  onChange={(e) => {
                    setBpm(e.target.value);
                    handleOnChangeBpm(e);
                  }}
                  className="w-full rounded-md border border-form-strokedark bg-form-input px-4 py-2.5 text-white focus:border-white focus:outline-none"
                />
              </div>
              <div className="w-full md:w-1/2">
                <label className="mb-2.5 block text-sm font-medium text-white">
                  Key
                </label>
                <input
                  type="text"
                  placeholder="Enter Key"
                  defaultValue={subProject.song_key}
                  onChange={(e) => {
                    setKey(e.target.value);
                    handleOnChangeKey(e);
                  }}
                  className="w-full rounded-md border border-form-strokedark bg-form-input px-4 py-2.5 text-white focus:border-white focus:outline-none"
                />
              </div>
              {canUpload && (
                <div>
                  <button
                    className="rounded-md bg-primary px-4 py-2 text-sm font-semibold text-white hover:bg-opacity-90"
                    type="button"
                    onClick={handleSubProjectDetails}
                  >
                    Update Song
                  </button>
                </div>
              )}
            </form>
          </div>
        ) : null}

        {activeTab === "demos" && (
          <div className="min-h-[350px] rounded border border-form-strokedark bg-form-input p-4">
            {uploadedFiles.length === 0 ? (
              <EmptyDemo
                canUpload={canUpload}
                uploadedFilesProgressData={{ progress, error, isUploading }}
                setDeleteFileId={setDeleteFileId}
                setEmployeeType={handleEmployeeType}
                setFileUploadType={handleUploadFileType}
                setFormData={handleDemoUploads}
              />
            ) : (
              <UploadedDemo
                canUpload={canUpload}
                uploadedFilesProgressData={{ progress, error, isUploading }}
                uploadedFiles={uploadedFiles}
                setDeleteFileId={setDeleteFileId}
                setEmployeeType={handleEmployeeType}
                setFileUploadType={handleUploadFileType}
                setFormData={handleDemoUploads}
              />
            )}
          </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={handleUpdateLyrics}
            />
          </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={handleWriterNotesModalClose}
          notes={subProject.notes}
        />
      )}
    </div>
  );
};

export default SubProject;
