import React from "react";
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
import { ClipLoader } from "react-spinners";
import FileUploadMultiple from "Components/fileUploadMultiple";
import UploadProgressBar from "Src/libs/uploadProgressBar";
import { useFileUpload } from "Src/libs/uploadFileHook";
import { AuthContext, tokenExpireError } from "Src/authContext";
import Select from "react-select";
import MkdSDK from "Utils/MkdSDK";
import FileUpload from "Components/Client/ClientViewProjectDetails/fileUpload";
import { GlobalContext, showToast } from "Src/globalContext";
import CustomSelect from "./CustomSelect";
import CustomSelect2 from "./CustomSelect2";
import {
  getSubProjectsByProjectIdAPI,
  updateSubProjectEmployeeCostAPI,
} from "Src/services/projectService";

const AddSongModal = ({
  isOpen,
  setIsOpen,
  onSubmit,
  writers,
  artists,
  engineers,
  mixSeasons,
}) => {
  console.log(mixSeasons);
  const { dispatch, state: authState } = React.useContext(AuthContext);

  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: "",
  });
  const { dispatch: globalDispatch } = React.useContext(GlobalContext);
  const [fileValues, setFileValues] = React.useState([]);
  const [isUpload, setIsUpload] = React.useState(false);

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

  // Transform employees data for react-select
  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,
    })) || [];

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

  const handleArtistChange = (selectedOption) => {
    console.log(selectedOption);
    console.log(artistOptions);
    const selectedArtist = artistOptions.find(
      (artist) => artist.value == selectedOption
    );
    console.log(selectedArtist);
    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 handleArtistCostChange = async (data) => {
    try {
      const result = await updateSubProjectEmployeeCostAPI(data);
      if (!result.error) {
        showToast(globalDispatch, result.message, 2000);
        await getSubProjectsByProjectIdAPI();
        return;
      } else {
        showToast(globalDispatch, result.message, 2000, "error");
        return;
      }
    } catch (error) {
      tokenExpireError(dispatch, error.message);
    }
  };

  const handleWriterCostChange = async (data) => {
    try {
      const result = await updateSubProjectEmployeeCostAPI(data);
      if (!result.error) {
        showToast(globalDispatch, result.message, 2000);
        await getSubProjectsByProjectIdAPI();
        return;
      } else {
        showToast(globalDispatch, result.message, 2000, "error");
        return;
      }
    } catch (error) {
      tokenExpireError(dispatch, error.message);
    }
  };

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

  // Replace formData states with fileValues states
  const [instrumentalFileValues, setInstrumentalFileValues] = React.useState(
    []
  );
  const [masterFileValues, setMasterFileValues] = React.useState([]);

  const handleSubmit = async (e) => {
    e.preventDefault();
    const sdk = new MkdSDK();

    // Validate all required fields
    if (!songData.mixSeason) {
      showToast(
        globalDispatch,
        `Please fill in all required fields`,
        5000,
        "error"
      );
      return;
    }

    try {
      // 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 employees = [];
      if (songData.writer) {
        employees.push({
          id: songData.writer,
          type: "writer",
          cost: songData.writerCost,
        });
      }
      if (songData.artist) {
        employees.push({
          id: songData.artist,
          type: "artist",
          cost: songData.artistCost,
        });
      }
      if (songData.engineer) {
        employees.push({
          id: songData.engineer,
          type: "engineer",
          cost: songData.engineerCost,
        });
      }

      const payload = {
        type_name: songData.songTitle || "Song",
        eight_count: 0,
        employees,
        is_song: 1,
        mix_season: songData?.mixSeason,
        song_type: songData.songType,
        genre: songData.genre,
        lyrics: songData.lyrics,
        song_title_key: songData.songKey,
        bpm_lyrics: songData.lyrics,
        // attachments: [instrumentalPath, masterPath].filter(Boolean).join(","),
        bpm: Number(songData.bpm),
        song_key: songData.songKey,
        is_file: 0,
        gender: songData?.artist_gender,
        file_cost: 0,
        status: 0,
      };

      const result = await sdk.callRawAPI(
        "/v3/api/custom/equality_record/project/sub_project/without_project_id",
        payload,
        "POST"
      );
      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.result,
              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.result,
              workorder_id: 0,
              employee_id: songData.engineer || null,
              employee_type: "engineer",
              type: "master",
              attachments: masterPath,
              is_from_admin: 1,
            },
            "POST"
          );
        }

        setIsOpen(false);
        if (onSubmit) onSubmit();
      }
    } catch (error) {
      console.error("Error creating song:", error);
      setIsUpload(false);
    }
  };

  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 h-[90vh] w-full 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="fa-solid fa-music"
              className="text-xl text-primary"
            />
            <h3 className="text-xl font-medium text-white">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"
        >
          <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
                  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
                  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
                  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
                  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
                  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-[44px] !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"
                onChange={(value) => {
                  setSongData((prev) => ({
                    ...prev,

                    writerCost: value || "",
                  }));
                }}
                value={songData.writerCost}
                className="px-4 w-full h-11 text-white rounded border 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-[44px] !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"
                onChange={(value) => {
                  setSongData((prev) => ({
                    ...prev,

                    artistCost: value || "",
                  }));
                }}
                value={songData.artistCost}
                className="px-4 w-full h-11 text-white rounded border 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-[44px] !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}
                onChange={(value) => {
                  setSongData((prev) => ({
                    ...prev,

                    engineerCost: value || "",
                  }));
                }}
                className="px-4 w-full h-11 text-white rounded border 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
                  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>

            {/* Add these fields before the file upload section */}

            {/* 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" />
              ) : (
                "Create Song"
              )}
            </button>
          </div>
        </div>
      </div>
    </div>
  );
};

export default AddSongModal;
