import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
import {
  addMediaAPI,
  retrieveAllMediaAPI,
} from "Src/services/clientProjectDetailsService";
import React from "react";
import { useParams } from "react-router";
import { ClipLoader } from "react-spinners";
import FileUpload from "./ClientViewProjectDetails/fileUpload";
import { GlobalContext, showToast } from "Src/globalContext";
import UploadProgressBar from "Src/libs/uploadProgressBar";
import { useFileUpload } from "Src/libs/uploadFileHook";

const ClientAddMusicModal = ({ isOpen, setIsOpen, setMusicList }) => {
  const projectId = 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 [isUpload, setIsUpload] = React.useState(false);
  const {
    uploadFiles: uploadS3FilesAPI,
    progress,
    error,
    isUploading,
  } = useFileUpload();

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

      // setIsLoading(true);
      const result = await uploadS3FilesAPI(formData);
      if (!result.error) {
        showToast(globalDispatch, `Music Uploaded`, 5000);

        setFile(result.attachments);
        setIsUpload(false);
      }
    } catch (error) {
      setIsUpload(false);
      throw error;
    }
  };

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

    if (!File) {
      showToast(globalDispatch, `Upload file before submission`, 5000, "error");
    } else {
      try {
        setLoader(true);
        const payload = {
          project_id: projectId.id,
          url: File,
          type: type,
          description: description,
          is_paid: 1,
          is_music: 1,
          status: 1,
        };
        const res = await addMediaAPI(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 === 1);
          setMusicList(filter);
        }
        setLoader(false);
        setIsOpen(false);
      } catch (error) {
        setLoader(false);
        throw error;
      }
    }
  };
  return (
    <div className="fixed inset-0 z-50 flex items-center justify-center">
      {/* Backdrop */}
      <div
        className="fixed inset-0 bg-black/50 backdrop-blur-sm"
        onClick={() => setIsOpen(false)}
      />

      {/* Modal Container */}
      <div className="shadow-default border-form0strokedark w-full max-w-xl transform rounded border bg-boxdark transition-all">
        {/* Modal Header */}
        <div className="flex items-center justify-between border-b border-stroke 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">
              Add Music/Licenses
            </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={onSubmit} className="p-6">
          <div className="space-y-4">
            {/* Type Input */}
            <div className="flex flex-col gap-2">
              <label className="text-sm font-medium text-bodydark2">Type</label>
              <div className="flex h-11 items-center rounded border border-form-strokedark bg-form-input">
                <input
                  value={type}
                  required
                  onChange={(e) => setType(e.target.value)}
                  type="text"
                  className="w-full rounded-sm bg-transparent px-4 text-white outline-none placeholder:text-bodydark2"
                  placeholder="Full Mix, License Document..."
                />
              </div>
            </div>

            {/* Description Input */}
            <div className="flex flex-col gap-2">
              <label className="text-sm font-medium text-bodydark2">
                Description
              </label>
              <div className="flex h-11 items-center rounded border border-form-strokedark bg-form-input">
                <input
                  required
                  value={description}
                  onChange={(e) => setDescription(e.target.value)}
                  type="text"
                  className="w-full rounded-sm bg-transparent px-4 text-white outline-none placeholder:text-bodydark2"
                  placeholder="Add Description"
                />
              </div>
            </div>

            {/* File Upload */}
            <div className="flex flex-col gap-2">
              <label className="text-sm font-medium text-bodydark2">
                Music/License File
              </label>
              <FileUpload
                label="Music/Licenses"
                setFormData={handleFileUploads}
                isUploading={isUpload}
              />
            </div>

            {/* Upload Progress */}
            <UploadProgressBar progress={progress} isUploading={isUploading} />
          </div>
        </form>

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

export default ClientAddMusicModal;
