import React, { useState } 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 WorkOrderUploadedMaster from "../WorkOrderUploadedMaster";
import WorkOrderEmptyMaster from "../WorkOrderEmptyMaster";
import WorkOrderLyrics from "../WorkOrderLyrics";
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 WriterArtistEngineerSubProject = ({
  subProject,
  workOrderDetails,
  uploadedMasterFiles,
  setLyrics,
  setDeleteFileId,
  setSubProjectDetails,
}) => {
  const navigate = useNavigate();

  const { state: authState } = React.useContext(AuthContext);
  const { dispatch: globalDispatch, state } = React.useContext(GlobalContext);
  const {
    uploadS3FilesAPI: uploadS3FilesMasterAPI,
    progress: progressMaster,
    error: errorMaster,
    isUploading: isUploadingMaster,
  } = useS3UploadMaster();

  const { subproject_update } = state;
  const [showIdeasNotesModal, setShowIdeasNotesModal] = React.useState(false);

  const { songSubProjectsEditWorkOrder } = state;

  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] = useState("master");

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

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

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

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

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

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

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

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

    if (songIndex > -1) {
      const updatedSongs = [...songSubProjectsEditWorkOrder];
      updatedSongs[songIndex].song_key = e.target.value;
      updatedSongs[songIndex].is_song = 1;
      globalDispatch({
        type: "SET_SONG_SUB_PROJECTS_EDIT_WORK_ORDER",
        payload: updatedSongs,
      });
    } else {
      globalDispatch({
        type: "SET_SONG_SUB_PROJECTS_EDIT_WORK_ORDER",
        payload: [
          ...songSubProjectsEditWorkOrder,
          {
            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 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,
          is_from_admin: 1,
        };

        const fileUploadDataResult = await uploadFilesDataAPI(payload);
        if (!fileUploadDataResult.error) {
          showToast(globalDispatch, "Files updated successfully", 5000);
          console.log(subproject_update);
          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");
    }
  };
  console.log("pdoodo");
  React.useEffect(() => {
    if (subProject) {
      console.log(subProject.type_name, subProject.bpm, subProject.song_key);
      setSongTitle(subProject.type_name);
      setBpm(subProject.bpm);
      setKey(subProject.song_key);
    }
  }, [subProject]);

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

  return (
    <div className="shadow-default mt-10 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="font-semibold text-blue-500 hover:text-blue-400"
              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">
        <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>
        ) : null}
        {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 === "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 === "details" && subProject.is_song && (
          <div className="min-h-[350px] border border-form-strokedark bg-form-input p-4">
            <div className="flex flex-col gap-4">
              <div className="w-[50%]">
                <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="flex w-[50%] flex-row gap-3">
                <div className="basis-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="basis-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>
              </div>
              <div className="col-span-12">
                <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>
            </div>
          </div>
        )}

        {activeTab === "master" && (
          <div className="rounded border border-form-strokedark bg-form-input p-4">
            {uploadedMasterFiles.length > 0 ? (
              <WorkOrderUploadedMaster
                uploadedFiles={uploadedMasterFiles}
                setDeleteFileId={setDeleteFileId}
              />
            ) : (
              <WorkOrderEmptyMaster
                setEmployeeType={handleEmployeeType}
                setFileUploadType={handleUploadFileType}
                setFormData={handleMasterUploads}
              />
            )}
          </div>
        )}

        {activeTab === "lyrics" && (
          <div className="min-h-[350px] rounded border border-form-strokedark bg-form-input p-4">
            <WorkOrderLyrics
              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
          theme={subProject.survey.theme_of_the_routine}
          ideas={subProject.ideas}
          setModalClose={() => setShowIdeasNotesModal(false)}
          notes={subProject.notes}
        />
      )}
    </div>
  );
};

export default WriterArtistEngineerSubProject;
