import React, { useState } from "react";
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
import { ClipLoader } from "react-spinners";
import FileUpload from "Components/Client/ClientViewProjectDetails/fileUpload";
import UploadProgressBar from "Src/libs/uploadProgressBar";
import { useFileUpload } from "Src/libs/uploadFileHook";
import { GlobalContext, showToast } from "Src/globalContext";
import { updateSubProjectDetailsAPI } from "Src/services/projectService";
import MkdSDK from "Utils/MkdSDK";

const EditSongModal = ({ isOpen, setIsOpen, songData, onSubmit }) => {
  const { dispatch: globalDispatch } = React.useContext(GlobalContext);
  const [formData, setFormData] = useState(songData);
  const [instrumentalFileValues, setInstrumentalFileValues] = useState([]);
  const [masterFileValues, setMasterFileValues] = useState([]);
  const [isUpload, setIsUpload] = useState(false);
  console.log(songData, "songdata");
  const {
    uploadFiles: uploadFilesAPI,
    progress,
    error,
    isUploading,
  } = useFileUpload();

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

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

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

      if (instrumentalFileValues.length > 0) {
        setIsUpload(true);
        const instrumentalFormData = new FormData();
        for (const file of instrumentalFileValues) {
          instrumentalFormData.append("files", file);
        }

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

      if (masterFileValues.length > 0) {
        setIsUpload(true);
        const masterFormData = new FormData();
        for (const file of masterFileValues) {
          masterFormData.append("files", file);
        }

        const masterResult = await uploadFilesAPI(masterFormData);
        if (!masterResult.error) {
          masterPath = masterResult.attachments;
        }
      }
      setIsUpload(false);

      const sdk = new MkdSDK();

      // Update song details
      const result = await updateSubProjectDetailsAPI({
        subproject_id: formData.id,
        type_name: formData.songTitle,
        song_type: formData.songType,
        genre: formData.genre,
        lyrics: formData.lyrics,
        song_key: formData.songKey,
        bpm: Number(formData.bpm),
        gender: formData.artist_gender,
      });

      if (instrumentalPath) {
        await sdk.callRawAPI(
          "/v3/api/custom/equality_record/work_order/public/upload_files_data",
          {
            project_id: 0,
            subproject_id: formData.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: formData.id,
            workorder_id: 0,
            employee_id: songData.engineer || null,
            employee_type: "engineer",
            type: "master",
            attachments: masterPath,
            is_from_admin: 1,
          },
          "POST"
        );
      }

      if (result.error) {
        throw new Error(result.message);
      }

      showToast(globalDispatch, "Song updated successfully", 5000, "success");
      setIsOpen(false);
      if (onSubmit) onSubmit();
    } catch (error) {
      console.error("Error updating song:", error);
      showToast(globalDispatch, "Failed to update song", 5000, "error");
      setIsUpload(false);
    }
  };

  return (
    <div className="fixed inset-0 z-50 flex items-center justify-center">
      <div
        className="fixed inset-0 bg-black/50 backdrop-blur-sm"
        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 items-center justify-between border-b border-strokedark px-6 py-4">
          <div className="flex items-center gap-3">
            <FontAwesomeIcon
              icon="fa-solid fa-music"
              className="text-xl text-primary"
            />
            <h3 className="text-xl font-medium text-white">Edit 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">
            {/* Song Details */}
            <div className="col-span-2 grid grid-cols-3 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={formData.songTitle}
                  onChange={(e) =>
                    handleInputChange("songTitle", e.target.value)
                  }
                  className="h-11 w-full rounded border border-form-strokedark bg-form-input px-4 text-white outline-none"
                  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={formData.songKey}
                  onChange={(e) => handleInputChange("songKey", e.target.value)}
                  className="h-11 w-full rounded border border-form-strokedark bg-form-input px-4 text-white outline-none"
                  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={formData.bpm}
                  onChange={(e) => handleInputChange("bpm", e.target.value)}
                  className="h-11 w-full rounded border border-form-strokedark bg-form-input px-4 text-white outline-none"
                  placeholder="Enter BPM"
                />
              </div>
            </div>

            {/* Additional Fields */}
            <div className="col-span-2 grid grid-cols-3 gap-4">
              <div className="flex flex-col gap-2">
                <label className="text-sm font-medium text-bodydark">
                  Song Type
                </label>
                <input
                  required
                  type="text"
                  value={formData.songType}
                  onChange={(e) =>
                    handleInputChange("songType", e.target.value)
                  }
                  className="h-11 w-full rounded border border-form-strokedark bg-form-input px-4 text-white outline-none"
                  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={formData.genre}
                  onChange={(e) => handleInputChange("genre", e.target.value)}
                  className="h-11 w-full rounded border border-form-strokedark bg-form-input px-4 text-white outline-none"
                  placeholder="Enter genre"
                />
              </div>

              <div className="flex flex-col gap-2">
                <label className="text-sm font-medium text-bodydark">
                  Artist Gender
                </label>
                <input
                  type="text"
                  value={formData.artist_gender}
                  onChange={(e) =>
                    handleInputChange("artist_gender", e.target.value)
                  }
                  className="h-11 w-full rounded border border-form-strokedark bg-form-input px-4 text-white outline-none"
                  placeholder="Enter artist gender"
                />
              </div>
            </div>

            <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={formData.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>

            {/* File Upload Sections */}
            <div className="col-span-2">
              <h2 className="text-sm font-medium text-bodydark">
                Instrumental
              </h2>
              {songData?.admin_writer_instrumentals && (
                <div className="custom-overflow mb-4 max-h-[180px] overflow-y-auto">
                  <h4 className="mb-2 text-sm font-medium">Current Files:</h4>
                  <div className="rounded bg-boxdark-2 p-2">
                    {typeof songData?.admin_writer_instrumentals ===
                    "string" ? (
                      <div className="flex items-center gap-2">
                        <FontAwesomeIcon icon="fa-solid fa-file-audio" />
                        <span>{songData?.admin_writer_instrumentals}</span>
                      </div>
                    ) : (
                      songData?.admin_writer_instrumentals?.map((file, i) => (
                        <div key={i} className="flex items-start gap-2">
                          <FontAwesomeIcon icon="fa-solid fa-file-audio" />
                          <a
                            style={{ overflowWrap: "anywhere" }}
                            href={file.url}
                            target="_blank"
                            rel="noopener noreferrer"
                            className="inline-block whitespace-break-spaces break-words text-primary hover:underline"
                          >
                            {file.url.split("/").pop()}
                          </a>
                        </div>
                      ))
                    )}
                  </div>
                </div>
              )}
              <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>
              {songData?.masters && (
                <div className="custom-overflow mb-4 max-h-[180px] overflow-y-auto">
                  <h4 className="mb-2 text-sm font-medium">Current Files:</h4>
                  <div className="rounded bg-boxdark-2 p-2">
                    {typeof songData?.masters === "string" ? (
                      <div className="flex items-center gap-2">
                        <FontAwesomeIcon icon="fa-solid fa-file-audio" />
                        <span>{songData?.masters}</span>
                      </div>
                    ) : (
                      songData?.masters?.map((file, i) => (
                        <div key={i} className="flex items-start gap-2">
                          <FontAwesomeIcon icon="fa-solid fa-file-audio" />
                          <a
                            style={{ overflowWrap: "anywhere" }}
                            href={file.url}
                            target="_blank"
                            rel="noopener noreferrer"
                            className="inline-block whitespace-break-spaces break-words text-primary hover:underline"
                          >
                            {file.url.split("/").pop()}
                          </a>
                        </div>
                      ))
                    )}
                  </div>
                </div>
              )}
              <FileUpload
                label="Master"
                isUploading={isUpload}
                setFileValues={setMasterFileValues}
                fileValues={masterFileValues}
              />
            </div>

            {/* Progress Bar */}
            <div className="col-span-2">
              <UploadProgressBar
                progress={progress}
                isUploading={isUploading}
              />
            </div>
          </div>
        </form>

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

export default EditSongModal;
