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

import { GlobalContext, showToast } from "Src/globalContext";
import { useFileUpload } from "Src/libs/uploadFileHook";
import UploadProgressBar from "Src/libs/uploadProgressBar";
import {
  addMediaAPI,
  retrieveAllMediaAPI,
} from "Src/services/clientProjectDetailsService";
import React from "react";
import { useParams } from "react-router";
import { ClipLoader } from "react-spinners";
import MusicUploadBox from "./MusicUploadBox";

const ClientAddMusicModal = ({
  isOpen,
  setIsOpen,
  setMusicList,
  setMusic_ids,
  music_ids,
}) => {
  const params = useParams();
  const projectId = params?.project_id ? params?.project_id : params?.id;
  const { dispatch: globalDispatch } = React.useContext(GlobalContext);
  const [type, setType] = React.useState("");
  const [loader, setLoader] = React.useState(false);
  const [description, setDescription] = React.useState("");
  const [isUpload, setIsUpload] = React.useState(false);
  const [fileValues, setFileValues] = React.useState([]);
  const {
    uploadFiles: uploadFilesAPI,
    progress,
    error,
    isUploading,
  } = useFileUpload();

  const handleFileUploads = async (formData) => {
    try {
      setLoader(true);
      setIsUpload(true);
      const result = await uploadFilesAPI(formData);
      if (!result.error) {
        setIsUpload(false);
        return result;
      } else if (result.error) {
        showToast(
          globalDispatch,
          `Upload File before submission`,
          5000,
          "error"
        );
        return null;
      }
    } catch (error) {
      setIsUpload(false);
      return null;
    }
  };

  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 onSubmit = async (e) => {
    e.preventDefault();
    if (!fileValues || fileValues.length === 0) {
      showToast(globalDispatch, "No file selected", 5000, "error");
      return;
    }

    if (!validateFileSize(fileValues)) return;

    const formData = new FormData();
    for (const file of fileValues) {
      if (!validateFileSize(file)) continue;
      formData.append("files", file);
    }

    try {
      setLoader(true);
      const resulte = await uploadFilesAPI(formData);

      const payload = {
        project_id: projectId,
        url: resulte?.attachments,
        type: type,
        description: description,
        is_paid: 1,
        is_music: 1,
        status: 1,
      };

      if (
        !resulte?.attachments ||
        resulte.attachments.length === 0 ||
        resulte.attachments === "[]" ||
        (typeof resulte.attachments === "string" &&
          JSON.parse(resulte.attachments).length === 0)
      ) {
        showToast(
          globalDispatch,
          `Upload track before submission`,
          5000,
          "error"
        );
        return;
      } else if (
        !payload.url ||
        payload.url.length === 0 ||
        (typeof payload.url === "string" &&
          JSON.parse(payload.url).length === 0)
      ) {
        showToast(globalDispatch, `Invalid attachment URL`, 5000, "error");
        setLoader(false);
        return;
      } else {
        const res = await addMediaAPI(payload);

        if (res.error) {
          showToast(
            globalDispatch,
            `Failed to add media: ${res.error}`,
            5000,
            "error"
          );
          setLoader(false);
          return;
        }

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

        if (!result.error) {
          const filter = result.list.filter((elem) => elem.is_music === 1);
          let musicId = filter?.[0]?.id;
          music_ids && setMusic_ids([...music_ids, musicId]);
          setMusicList(filter);
        }
        setLoader(false);
        setIsOpen(false);
      }
    } catch (error) {
      setLoader(false);
      showToast(
        globalDispatch,
        `An error occurred: ${error.message}`,
        5000,
        "error"
      );
    }
  };

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

      {/* Modal Container */}
      <div className="w-full max-w-xl rounded border transition-all transform shadow-default border-strokedark bg-boxdark">
        {/* Modal Header */}
        <div className="flex justify-between items-center px-6 py-4 border-b border-stroke">
          <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 Music</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">
            {/* Upload Box */}
            <div className="flex flex-col gap-2">
              <MusicUploadBox
                isUploading={isUpload}
                setFileValues={setFileValues}
                fileValues={fileValues}
              />
            </div>

            {/* Type Input */}
            <div className="flex flex-col gap-2">
              <label className="text-sm font-medium text-bodydark2">Type</label>
              <div className="flex items-center h-11 rounded border border-form-strokedark bg-form-input">
                <select
                  value={type}
                  required
                  onChange={(e) => setType(e.target.value)}
                  className="px-4 w-full text-white bg-transparent rounded appearance-none cursor-pointer outline-none"
                >
                  <option value="" disabled className="bg-boxdark">
                    Select a type...
                  </option>
                  <option value="Music" className="bg-boxdark">
                    Music
                  </option>
                  <option value="Edit" className="bg-boxdark">
                    Edit
                  </option>
                  <option value="Video with Music" className="bg-boxdark">
                    Video with Music
                  </option>
                  <option value="Other" className="bg-boxdark">
                    Other
                  </option>
                </select>
              </div>
            </div>

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

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

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

export default ClientAddMusicModal;
