import React from "react";
import { GlobalContext, showToast } from "Src/globalContext";
import {
  uploadS3FilesAPI,
  uploadFilesDataAPI,
} from "Src/services/workOrderService";
import Lyrics from "./Lyrics";
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";

const SubProject = ({
  canUpload = true,
  workOrderDetails,
  subProject,
  uploadedFiles,
  setDeleteFileId,
  setLyrics,
  setSubProjectDetails,
}) => {
  const { dispatch: globalDispatch, state } = React.useContext(GlobalContext);
  const {
    uploadS3FilesAPI: uploadS3FilesMasterAPI,
    progress: progressMaster,
    error: errorMaster,
    isUploading: isUploadingMaster,
  } = useS3UploadMaster();
  const {
    uploadS3FilesAPI: uploadS3FilesMasterAPI2,
    progress: progressMaster2,
    error: errorMaster2,
    isUploading: isUploadingMaster2,
  } = useS3UploadMaster();
  const { songSubProjects, subproject_update } = state;

  const [songTitle, setSongTitle] = React.useState(subProject.type);
  const [bpm, setBpm] = React.useState(subProject.bpm);
  const [key, setKey] = React.useState(subProject.song_key);
  const [showIdeasNotesModal, setShowIdeasNotesModal] = React.useState(false);
  const [activeTab, setActiveTab] = React.useState("master");

  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 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 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="mb-2 block w-full max-w-5xl rounded-md border border-gray-500 bg-gray-800 p-5 shadow">
      <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>

      <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>

      <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">
                <label className="mb-2 block text-xs font-bold tracking-wide text-white">
                  Song Title
                </label>
                <input
                  className="mb-3 block w-full appearance-none rounded border border-gray-500 bg-gray-700 px-4 py-3 leading-tight text-white placeholder:text-gray-200 focus:bg-gray-700 focus:outline-none"
                  type="text"
                  placeholder="Enter Song Title"
                  defaultValue={subProject.type_name}
                  onChange={(e) => {
                    setSongTitle(e.target.value);
                    handleOnChangeTitle(e);
                  }}
                />
              </div>

              <div className="w-full">
                <label className="mb-2 block text-xs font-bold tracking-wide text-white">
                  BPM
                </label>
                <input
                  className="mb-3 block w-full appearance-none rounded border border-gray-500 bg-gray-700 px-4 py-3 leading-tight text-white placeholder:text-gray-200 focus:bg-gray-700 focus:outline-none"
                  type="text"
                  placeholder="Enter BPM"
                  defaultValue={subProject.bpm}
                  onChange={(e) => {
                    setBpm(e.target.value);
                    handleOnChangeBpm(e);
                  }}
                />
              </div>

              <div className="w-full">
                <label className="mb-2 block text-xs font-bold tracking-wide text-white">
                  Key
                </label>
                <input
                  className="mb-3 block w-full appearance-none rounded border border-gray-500 bg-gray-700 px-4 py-3 leading-tight text-white placeholder:text-gray-200 focus:bg-gray-700 focus:outline-none"
                  type="text"
                  placeholder="Enter Key"
                  defaultValue={subProject.song_key}
                  onChange={(e) => {
                    setKey(e.target.value);
                    handleOnChangeKey(e);
                  }}
                />
              </div>

              {canUpload && (
                <div className="flex justify-start">
                  <button
                    className="rounded bg-green-600 px-2 py-1 text-sm font-bold text-white hover:bg-green-700"
                    type="button"
                    onClick={handleSubProjectDetails}
                  >
                    Update Song
                  </button>
                </div>
              )}
            </form>
          </div>
        ) : null}

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