import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";

import {
  addMediaAPI,
  retrieveAllMediaAPI,
} from "Src/services/clientProjectDetailsService";
import {
  deleteS3FileAPI,
  uploadS3FilesAPI,
} from "Src/services/workOrderService";
import React from "react";
import { useParams } from "react-router";
import { ClipLoader } from "react-spinners";
import FileUpload from "../../Client/ClientViewProjectDetails/fileUpload";
import { GlobalContext, showToast } from "Src/globalContext";
import {
  addSubProjectAPI,
  deleteOneFileAPI,
  getProjectDetailsAPI,
} from "Src/services/projectService";
import { tokenExpireError } from "Src/authContext";
import { progress } from "framer-motion";
import AudioUpload from "Components/audioUpload";
import FileUploadMultiple from "Components/fileUploadMultiple";
import UploadProgressBar from "Src/libs/uploadProgressBar";
import { useFileUpload } from "Src/libs/uploadFileHook";

import CustomSelect2 from "Components/CustomSelect2";
import CustomSelect from "Components/CustomSelect";
import MkdSDK from "Utils/MkdSDK";

const AddFileSubProject = ({
  isOpen,
  setTempUploadCount,
  UploadCount,
  setIsOpen,
  id,
  mixSeasons,
  tempUploadCount,
  setUpdateSubprojectPayload,
  subprojectType,
  writers,
  artists,
  engineers,
}) => {
  const params = useParams();
  const { dispatch: globalDispatch } = React.useContext(GlobalContext);
  const [type, setType] = React.useState("");
  const [loader, setLoader] = React.useState(false);
  const [description, setDescription] = React.useState("");
  const [File, setFile] = React.useState("");
  const [fileValues, setFileValues] = React.useState([]);
  const [videoId, setVideoId] = React.useState("");

  const [isUpload, setIsUpload] = React.useState(false);
  console.log(tempUploadCount, UploadCount);
  console.log(subprojectType);
  console.log(mixSeasons, "NSNSN");

  const {
    uploadFiles: uploadFilesAPI,
    progress,
    error,
    isUploading,
  } = useFileUpload();

  const [instrumentalFileValues, setInstrumentalFileValues] = React.useState(
    []
  );
  const [masterFileValues, setMasterFileValues] = React.useState([]);

  // Add new state for song data
  const [songData, setSongData] = React.useState({
    songTitle: "",
    songKey: "",
    bpm: "",
    writer: null,
    writerCost: "",
    artist: null,
    artistCost: "",
    engineer: null,
    engineerCost: "",
    lyrics: "",
    artist_gender: "",
    genre: "",
    songType: "",
    status: "unassigned",
    mixSeason: "",
  });

  // Transform options for selects
  const writerOptions =
    writers?.map((writer) => ({
      value: writer.id,
      label: writer.name,
      cost: writer.writer_cost,
    })) || [];

  const artistOptions =
    artists?.map((artist) => ({
      value: artist.id,
      label: artist.name,
      cost: artist.artist_cost,
    })) || [];

  const engineerOptions =
    engineers?.map((engineer) => ({
      value: engineer.id,
      label: engineer.name,
      cost: engineer.engineer_cost,
    })) || [];

  // Add handlers for employee selection
  const handleWriterChange = (selectedOption) => {
    const selectedWriter = writerOptions.find(
      (writer) => writer.value == selectedOption
    );
    setSongData((prev) => ({
      ...prev,
      writer: selectedOption,
      writerCost: selectedWriter?.cost || "",
    }));
  };

  const handleArtistChange = (selectedOption) => {
    const selectedArtist = artistOptions.find(
      (artist) => artist.value == selectedOption
    );
    setSongData((prev) => ({
      ...prev,
      artist: selectedOption,
      artistCost: selectedArtist?.cost || "",
      artist_gender: selectedArtist?.gender || "",
    }));
  };

  const handleEngineerChange = (selectedOption) => {
    const selectedEngineer = engineerOptions.find(
      (engineer) => engineer.value == selectedOption
    );
    setSongData((prev) => ({
      ...prev,
      engineer: selectedOption,
      engineerCost: selectedEngineer?.cost || "",
    }));
  };

  const handleInputChange = (field, value) => {
    setSongData((prev) => ({
      ...prev,
      [field]: value,
    }));
  };

  console.log(mixSeasons, "songData");
  console.log(writerOptions, "writer");

  const handleDeleteFileSubmit = async (id) => {
    try {
      const result = await deleteOneFileAPI(id);
      if (!result.error) {
        if (result.file) {
          const s3delRes = await deleteS3FileAPI(result.file.url);
          if (!s3delRes.error) {
            showToast(globalDispatch, result.message, 5000);
            window.location.reload();
          }
        }
      } else {
        showToast(globalDispatch, result.message, 5000, "error");
      }
    } catch (error) {
      showToast(globalDispatch, error.message, 5000, "error");
    }
  };

  const uploadFiles = async (fileValues) => {
    if (!fileValues || fileValues.length === 0) {
      showToast(
        globalDispatch,
        "No file selected or File format not supported",
        5000,
        "error"
      );
      return;
    }

    if (!validateFileSize(fileValues)) return;

    const formData = new FormData();
    for (const file of fileValues) {
      // Ffm file size after conversion
      if (!validateFileSize(file)) continue;

      console.log(file.name);
      // Append converted file to FormData

      formData.append("files", file);
    }

    const res = await handleFileUploads(formData);

    return { res: res };
  };

  let maxFileSize = 500;

  const validateFileSize = (file) => {
    const fileSize = file.size / 1024 / 1024; // in MB
    if (fileSize > maxFileSize) {
      showToast(
        globalDispatch,
        `File size exceeds ${maxFileSize}MB. Please upload a smaller file.`,
        5000,
        "error"
      );
      return false;
    }
    return true;
  };

  const handleFileUploads = async (formData) => {
    try {
      setLoader(true);
      setIsUpload(true);

      // setIsLoading(true);
      const result = await uploadFilesAPI(formData);
      if (!result.error) {
        // showToast(globalDispatch, `Video Uploaded`, 5000);
        console.log(result);
        setVideoId(result?.id);
        setIsUpload(false);

        return result;
      } else if (result.error) {
        showToast(
          globalDispatch,
          `Upload File Inbefore submission`,
          5000,
          "error"
        );
        return null;
      }
    } catch (error) {
      setIsUpload(false);
      return null;
      throw error;
    }
  };

  console.log(fileValues);

  const handleSubmit = async (e) => {
    console.log(songData, "songData");
    e.preventDefault();
    const sdk = new MkdSDK();

    if (isVoiceoverProject) {
      const { res: resulte } = await uploadFiles(fileValues);

      if (!resulte) {
        showToast(
          globalDispatch,
          `Upload file before submission`,
          5000,
          "error"
        );
      } else {
        try {
          setLoader(true);
          const payload = {
            is_file: true,
            subproject_id: id,
            files: JSON.parse(resulte.attachments),
            employee_type: "engineer",

            type: `Voiceover Upload ${tempUploadCount}`,
            type_name: `Voiceover Upload ${tempUploadCount}`,
            project_id: Number(params.id),
            lyrics: description,
            file_cost: Number(type),
          };
          const res = await setUpdateSubprojectPayload(payload);

          // const result = await retrieveAllMediaAPI({
          //   page: 1,
          //   limit: 10,
          //   filter: {
          //     project_id: projectId.id,
          //   },
          // });

          // if (!result.error) {
          //   const filter = result.list.filter((elem) => elem.is_music === (filter);
          // }
          setLoader(false);
          setIsOpen(false);
        } catch (error) {
          setLoader(false);
          throw error;
        }
      }
    }

    // Validate required fields
    if (
      !songData.songTitle ||
      !songData.songKey ||
      !songData.bpm ||
      !songData.mixSeason ||
      !songData.songType ||
      !songData.genre ||
      !songData.lyrics
    ) {
      console.log(songData, "songData");
      showToast(
        globalDispatch,
        `Please fill in all required fields`,
        5000,
        "error"
      );
      return;
    }

    if (instrumentalFileValues.length === 0 || masterFileValues.length === 0) {
      showToast(
        globalDispatch,
        `Please upload both Instrumental and Master files`,
        5000,
        "error"
      );
      return;
    }

    try {
      setLoader(true);

      // Handle file uploads first
      let instrumentalPath = "";
      let masterPath = "";

      if (instrumentalFileValues.length > 0) {
        setIsUpload(true);
        // Create FormData for instrumental file
        const instrumentalFormData = new FormData();
        for (const file of instrumentalFileValues) {
          // Add any file validation if needed
          // if (!validateFileSize(file)) continue;

          instrumentalFormData.append("files", file);
        }

        const instrumentalResult = await uploadFilesAPI(instrumentalFormData);
        if (!instrumentalResult.error) {
          instrumentalPath = instrumentalResult.attachments;
        }
      }

      if (masterFileValues.length > 0) {
        setIsUpload(true);
        // Create FormData for master file
        const masterFormData = new FormData();
        for (const file of masterFileValues) {
          // Add any file validation if needed
          // if (!validateFileSize(file)) continue;

          masterFormData.append("files", file);
        }

        const masterResult = await uploadFilesAPI(masterFormData);
        if (!masterResult.error) {
          masterPath = masterResult.attachments;
        }
      }
      setIsUpload(false);
      const payload = {
        is_file: true,
        subproject_id: id,

        type: `Song Upload ${tempUploadCount}`,
        type_name: songData.songTitle,

        lyrics: songData.lyrics,
        file_cost: Number(songData.engineerCost),
        song_type: songData.songType,
        genre: songData.genre,
        mix_season: songData.mixSeason,
        song_key: songData.songKey,
        bpm: songData.bpm,
        gender: songData.artist_gender,
        employees: [
          songData.writer && {
            id: songData.writer,
            type: "writer",
            cost: songData.writerCost,
          },
          songData.artist && {
            id: songData.artist,
            type: "artist",
            cost: songData.artistCost,
          },
          songData.engineer && {
            id: songData.engineer,
            type: "engineer",
            cost: songData.engineerCost,
          },
        ].filter(Boolean),
      };
      const result = await setUpdateSubprojectPayload(payload);

      // const result = await retrieveAllMediaAPI({
      //   page: 1,
      //   limit: 10,
      //   filter: {
      //     project_id: projectId.id,
      //   },
      // });

      // if (!result.error) {
      //   const filter = result.list.filter((elem) => elem.is_music === (filter);
      // }
      if (result) {
        // Upload instrumental file data
        if (instrumentalPath) {
          await sdk.callRawAPI(
            "/v3/api/custom/equality_record/work_order/public/upload_files_data",
            {
              project_id: 0,
              subproject_id: result.id,
              workorder_id: 0,
              employee_id: songData.writer || null,
              employee_type: "writer",
              type: "instrumental",
              attachments: instrumentalPath,
              is_from_admin: 1,
            },
            "POST"
          );
        }
        if (masterPath) {
          await sdk.callRawAPI(
            "/v3/api/custom/equality_record/work_order/public/upload_files_data",
            {
              project_id: 0,
              subproject_id: result.id,
              workorder_id: 0,
              employee_id: songData.engineer || null,
              employee_type: "engineer",
              type: "master",
              attachments: masterPath,
              is_from_admin: 1,
            },
            "POST"
          );
        }

        setIsOpen(false);
      }
      setLoader(false);
      setIsOpen(false);
    } catch (error) {
      setLoader(false);
      throw error;
    }
  };

  // Determine if this is a voiceover project
  const isVoiceoverProject = subprojectType
    ?.toLowerCase()
    .includes("voiceover");

  return (
    <div className="flex fixed inset-0 z-50 justify-center items-center">
      <div
        className="fixed inset-0 backdrop-blur-sm bg-black/50"
        onClick={() => setIsOpen(false)}
      />

      <div
        className={`shadow-default  w-full ${
          isVoiceoverProject ? "h-[75vh]" : "h-[90vh]"
        } max-w-xl transform rounded border border-strokedark bg-boxdark transition-all`}
      >
        {/* Header */}
        <div className="flex justify-between items-center px-6 py-4 border-b border-strokedark">
          <div className="flex gap-3 items-center">
            <FontAwesomeIcon
              icon={
                isVoiceoverProject
                  ? "fa-solid fa-microphone"
                  : "fa-solid fa-music"
              }
              className="text-xl text-primary"
            />
            <h3 className="text-xl font-medium text-white">
              {isVoiceoverProject ? "Add New Voiceover" : "Add New Song"}
            </h3>
          </div>
          <button
            onClick={() => setIsOpen(false)}
            className="hover:text-primary"
          >
            <FontAwesomeIcon icon="fa-solid fa-xmark" className="text-2xl" />
          </button>
        </div>

        {/* Form Content */}
        <form
          onSubmit={handleSubmit}
          className="custom-overflow max-h-[calc(90vh-150px)] overflow-y-auto p-6"
        >
          {isVoiceoverProject ? (
            // Voiceover form content
            <div className="space-y-4">
              {/* Cost Input */}
              <div className="flex flex-col gap-2">
                <label className="text-sm font-medium text-bodydark2">
                  Cost
                </label>
                <div className="flex items-center h-11 rounded border border-form-strokedark bg-form-input">
                  <input
                    type="text"
                    required
                    onChange={(e) => setType(e.target.value)}
                    className="px-4 w-full text-white bg-transparent rounded outline-none placeholder:text-bodydark2"
                    placeholder="Enter cost"
                  />
                </div>
              </div>

              {/* Lyrics Input */}
              <div className="flex flex-col gap-2">
                <label className="text-sm font-medium text-bodydark2">
                  Lyrics
                </label>
                <div className="flex rounded border border-form-strokedark bg-form-input">
                  <textarea
                    type="text"
                    name="notes"
                    required
                    value={description}
                    onChange={(e) => setDescription(e.target.value)}
                    className="w-full rounded bg-transparent px-4 py-2.5 text-white outline-none placeholder:text-bodydark2"
                    rows={4}
                    placeholder="Add lyrics"
                  />
                </div>
              </div>

              {/* File Upload */}
              <div className="flex flex-col gap-2">
                <label className="text-sm font-medium text-bodydark2">
                  Audio
                </label>
                <FileUploadMultiple
                  label="Audio"
                  isUploading={isUpload}
                  setFileValues={setFileValues}
                  fileValues={fileValues}
                />
              </div>

              {/* Upload Progress */}
              <UploadProgressBar
                progress={progress}
                isUploading={isUploading}
              />
            </div>
          ) : (
            <div className="grid grid-cols-2 gap-4">
              <div className="grid grid-cols-3 col-span-2 gap-4">
                <div className="flex flex-col gap-2">
                  <label className="text-sm font-medium text-bodydark">
                    Mix Season
                  </label>
                  <CustomSelect2
                    value={songData.mixSeason}
                    className="h-[44px]"
                    onChange={(value) => handleInputChange("mixSeason", value)}
                    options={mixSeasons}
                    label="Select Mix Season"
                  >
                    <option value="">Select Mix Season</option>
                    {mixSeasons.map((mixSeason) => (
                      <option value={mixSeason.value} key={mixSeason.value}>
                        {mixSeason.label}
                      </option>
                    ))}
                  </CustomSelect2>
                </div>

                <div className="flex flex-col gap-2">
                  <label className="text-sm font-medium text-bodydark">
                    Song Type
                  </label>
                  <input
                    required
                    type="text"
                    value={songData.songType}
                    onChange={(e) =>
                      handleInputChange("songType", e.target.value)
                    }
                    className="px-4 w-full h-11 text-white rounded border outline-none border-form-strokedark bg-form-input"
                    placeholder="Enter song type"
                  />
                </div>

                <div className="flex flex-col gap-2">
                  <label className="text-sm font-medium text-bodydark">
                    Genre
                  </label>
                  <input
                    required
                    type="text"
                    value={songData.genre}
                    onChange={(e) => handleInputChange("genre", e.target.value)}
                    className="px-4 w-full h-11 text-white rounded border outline-none border-form-strokedark bg-form-input"
                    placeholder="Enter genre"
                  />
                </div>
              </div>
              {/* Song Details Group */}
              <div className="grid grid-cols-3 col-span-2 gap-4 rounded-lg">
                <div className="flex flex-col gap-2">
                  <label className="text-sm font-medium text-bodydark">
                    Song Title
                  </label>
                  <input
                    required
                    type="text"
                    value={songData.songTitle}
                    onChange={(e) =>
                      handleInputChange("songTitle", e.target.value)
                    }
                    className="px-4 w-full h-11 text-white rounded border outline-none border-form-strokedark bg-form-input"
                    placeholder="Enter song title"
                  />
                </div>
                <div className="flex flex-col gap-2">
                  <label className="text-sm font-medium text-bodydark">
                    Key
                  </label>
                  <input
                    required
                    type="text"
                    value={songData.songKey}
                    onChange={(e) =>
                      handleInputChange("songKey", e.target.value)
                    }
                    className="px-4 w-full h-11 text-white rounded border outline-none border-form-strokedark bg-form-input"
                    placeholder="Enter key"
                  />
                </div>
                <div className="flex flex-col gap-2">
                  <label className="text-sm font-medium text-bodydark">
                    BPM
                  </label>
                  <input
                    required
                    type="number"
                    value={songData.bpm}
                    onChange={(e) => handleInputChange("bpm", e.target.value)}
                    className="px-4 w-full h-11 text-white rounded border outline-none border-form-strokedark bg-form-input"
                    placeholder="Enter BPM"
                  />
                </div>
              </div>

              {/* Personnel Costs */}
              <div className="flex flex-col gap-2">
                <label className="text-sm font-medium text-bodydark">
                  Writer
                </label>
                <CustomSelect2
                  onChange={handleWriterChange}
                  name="writer"
                  value={songData.writer}
                  label="Select Writer"
                  className="h-[36px] !w-64 rounded border-[1.5px] border-form-strokedark bg-form-input px-3 py-2 text-sm outline-none transition focus:border-primary active:border-primary disabled:cursor-default disabled:bg-whiter dark:border-form-strokedark dark:bg-form-input"
                >
                  <option value="">Select Writer</option>
                  {writerOptions.map((writer) => (
                    <option value={writer.value} key={writer.value}>
                      {writer.label}
                    </option>
                  ))}
                </CustomSelect2>
              </div>
              <div className="flex flex-col gap-2">
                <label className="text-sm font-medium text-bodydark">
                  Writer Cost
                </label>
                <input
                  type="number"
                  value={songData.writerCost}
                  readOnly
                  className="px-4 w-full h-11 text-white rounded border cursor-not-allowed outline-none border-form-strokedark bg-form-input"
                />
              </div>

              {/* Artist Fields */}
              <div className="flex flex-col gap-2">
                <label className="text-sm font-medium text-bodydark">
                  Artist
                </label>
                <CustomSelect2
                  onChange={handleArtistChange}
                  name="artist"
                  value={songData.artist}
                  label="Select Artist"
                  className="h-[36px] !w-64 rounded border-[1.5px] border-form-strokedark bg-form-input px-3 py-2 text-sm outline-none transition focus:border-primary active:border-primary disabled:cursor-default disabled:bg-whiter dark:border-form-strokedark dark:bg-form-input"
                >
                  <option value="">Select Artist</option>
                  {artistOptions.map((artist) => (
                    <option value={artist.value} key={artist.value}>
                      {artist.label}
                    </option>
                  ))}
                </CustomSelect2>
              </div>
              <div className="flex flex-col gap-2">
                <label className="text-sm font-medium text-bodydark">
                  Artist Cost
                </label>
                <input
                  type="number"
                  value={songData.artistCost}
                  readOnly
                  className="px-4 w-full h-11 text-white rounded border cursor-not-allowed outline-none border-form-strokedark bg-form-input"
                />
              </div>

              {/* Engineer Fields */}
              <div className="flex flex-col gap-2">
                <label className="text-sm font-medium text-bodydark">
                  Engineer
                </label>
                <CustomSelect2
                  onChange={handleEngineerChange}
                  name="engineer"
                  value={songData.engineer}
                  label="Select Engineer"
                  className="h-[36px] !w-64 rounded border-[1.5px] border-form-strokedark bg-form-input px-3 py-2 text-sm outline-none transition focus:border-primary active:border-primary disabled:cursor-default disabled:bg-whiter dark:border-form-strokedark dark:bg-form-input"
                >
                  <option value="">Select Engineer</option>
                  {engineerOptions.map((engineer) => (
                    <option value={engineer.value} key={engineer.value}>
                      {engineer.label}
                    </option>
                  ))}
                </CustomSelect2>
              </div>
              <div className="flex flex-col gap-2">
                <label className="text-sm font-medium text-bodydark">
                  Engineer Cost
                </label>
                <input
                  type="number"
                  value={songData.engineerCost}
                  readOnly
                  className="px-4 w-full h-11 text-white rounded border cursor-not-allowed outline-none border-form-strokedark bg-form-input"
                />
              </div>

              {/* Additional Fields */}
              <div className="col-span-2">
                <div className="flex flex-col gap-2">
                  <label className="text-sm font-medium text-bodydark">
                    Lyrics
                  </label>
                  <textarea
                    required
                    value={songData.lyrics}
                    onChange={(e) =>
                      handleInputChange("lyrics", e.target.value)
                    }
                    className="w-full rounded border border-form-strokedark bg-form-input px-4 py-2.5 text-sm text-white focus:border-primary focus:outline-none"
                    rows={4}
                    placeholder="Enter lyrics"
                  />
                </div>
              </div>

              {/* Update file upload sections to use separate handlers */}
              <div className="col-span-2">
                <h2 className="text-sm font-medium text-bodydark">
                  Instrumental
                </h2>
                <FileUpload
                  label="Instrumental"
                  isUploading={isUpload}
                  setFileValues={setInstrumentalFileValues}
                  fileValues={instrumentalFileValues}
                />
              </div>

              <div className="col-span-2">
                <h2 className="text-sm font-medium text-bodydark">Master</h2>
                <FileUpload
                  label="Master"
                  isUploading={isUpload}
                  setFileValues={setMasterFileValues}
                  fileValues={masterFileValues}
                />
              </div>

              {/* Add progress bar */}
              <div className="col-span-2">
                <UploadProgressBar
                  progress={progress}
                  isUploading={isUploading}
                />
              </div>
            </div>
          )}
        </form>

        {/* Footer */}
        <div className="px-6 py-4 border-t border-strokedark">
          <div className="flex gap-3 justify-end items-center">
            <button
              type="button"
              onClick={() => setIsOpen(false)}
              className="flex justify-center items-center px-6 py-2 text-sm font-medium rounded border border-strokedark bg-meta-4 text-bodydark"
            >
              Cancel
            </button>
            <button
              onClick={handleSubmit}
              className="flex justify-center items-center px-6 py-2 text-sm font-medium text-white rounded bg-primary hover:bg-opacity-90"
              disabled={isUploading}
            >
              {isUploading ? (
                <ClipLoader size={16} color="white" />
              ) : isVoiceoverProject ? (
                "Add Voiceover Upload"
              ) : (
                "Create Song Upload"
              )}
            </button>
          </div>
        </div>
      </div>
    </div>
  );
};

export default AddFileSubProject;
