import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
import React from "react";
import { useParams } from "react-router";
import { ClipLoader } from "react-spinners";
import { AuthContext } from "Src/authContext";
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 { uploadS3FilesAPI } from "Src/services/workOrderService";
import VideoUploadBox from "./VideoUploadBox";

const ClientAddVideoModal = ({
  isOpen,
  projectIDVIDEO = null,
  setIsOpen,
  setVideoList,
  video_ids,
  setVideo_ids,
}) => {
  const params = useParams();
  const projectId = projectIDVIDEO
    ? projectIDVIDEO
    : params?.project_id
    ? params?.project_id
    : params?.id;
  const [type, setType] = React.useState("");
  const [loader, setLoader] = React.useState(false);
  const [description, setDescription] = React.useState("");
  const [videoId, setVideoId] = React.useState("");
  const [fileValues, setFileValues] = React.useState([]);
  const [isUpload, setIsUpload] = React.useState(false);

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

  const { dispatch: globalDispatch } = React.useContext(GlobalContext);

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

  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();
    let fileName;
    for (const file of fileValues) {
      if (!validateFileSize(file)) continue;
      fileName = file.name.slice(0, -4);
      formData.append("files", file);
    }

    try {
      setLoader(true);
      const resulte = await uploadFilesAPI(formData);
      if (!resulte) {
        showToast(
          globalDispatch,
          `Upload video before submission`,
          5000,
          "error"
        );
      }

      if (resulte) {
        const payload = {
          project_id: projectId,
          url: resulte?.attachments,
          type: type,
          description: description,
          is_paid: 1,
          is_music: 0,
          status: 1,
        };
        const res = await addMediaAPI(payload);

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

        if (!result.error) {
          const filter = result.list.filter((elem) => elem.is_music === 0);
          let videoId = filter?.[0]?.id;
          video_ids && setVideo_ids([...video_ids, videoId]);
          setVideoList(filter);
          setLoader(false);
          setIsOpen(false);
          showToast(globalDispatch, `Video Uploaded`, 5000);
        }
        setLoader(false);
        setIsOpen(false);
      }
    } catch (error) {
      showToast(globalDispatch, `Video Upload Failed`, 5000, error);
      setLoader(false);
      throw error;
    }
  };

  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;
  };

  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 w-full max-w-xl transform rounded border border-strokedark 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-video"
              className="text-xl text-primary"
            />
            <h3 className="text-xl font-medium text-white">Add Video</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">
            {/* Video Upload */}
            <div className="flex flex-col gap-2">
              <VideoUploadBox
                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 h-11 items-center rounded border border-form-strokedark bg-form-input">
                <select
                  value={type}
                  required
                  onChange={(e) => setType(e.target.value)}
                  className="w-full cursor-pointer appearance-none rounded bg-transparent px-4 text-white outline-none"
                >
                  <option value="" disabled className="bg-boxdark">
                    Select a type...
                  </option>
                  <option value="Full Out" className="bg-boxdark">
                    Full Out
                  </option>
                  <option value="Opening" className="bg-boxdark">
                    Opening
                  </option>
                  <option value="Tumbling" className="bg-boxdark">
                    Tumbling
                  </option>
                  <option value="Stunts" className="bg-boxdark">
                    Stunts
                  </option>
                  <option value="Pyramid" className="bg-boxdark">
                    Pyramid
                  </option>
                  <option value="Dance" className="bg-boxdark">
                    Dance
                  </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 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 bg-transparent px-4 text-white outline-none placeholder:text-bodydark2"
                  placeholder="Walk through, full out, additional details..."
                />
              </div>
            </div>

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

        {/* Footer */}
        <div className="border-t border-stroke 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-form-input px-6 py-2 text-sm font-medium text-bodydark1"
            >
              Close
            </button>
            <button
              onClick={onSubmit}
              className="flex items-center justify-center rounded 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 Video"}
            </button>
          </div>
        </div>
      </div>
    </div>
  );
};

export default ClientAddVideoModal;
