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

import { useParams } from "react-router";
import { ClipLoader } from "react-spinners";
import { GlobalContext, showToast } from "Src/globalContext";
import { useFileUpload } from "Src/libs/uploadFileHook";
import UploadProgressBar from "Src/libs/uploadProgressBar";
import { CreateTrackAPI } from "Src/services/countTracksService";
import { uploadS3FilesAPI } from "Src/services/workOrderService";
import AudioUpload from "./audioUpload";

const ClientAddTrackModal = ({
  isOpen,
  setIsOpen,
  setVideoList,
  getData,
  user_id = null,
}) => {
  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);

      // setIsLoading(true);
      const result = await uploadS3FilesAPI(formData);
      if (!result.error) {
        // showToast(globalDispatch, `Video Uploaded`, 5000);
        console.log(result);
        setVideoId(result?.id);
        setIsUpload(false);

        return result;
      } else if (result.error) {
        showToast(
          globalDispatch,
          `Upload File Inbefore submission`,
          5000,
          "error"
        );
        return null;
      }
    } catch (error) {
      setIsUpload(false);
      return null;
      throw error;
    }
  };

  const uploadFiles = async (fileValues) => {
    if (!fileValues || fileValues.length === 0) {
      showToast(
        globalDispatch,
        "No file selected or File format not supported",
        5000,
        "error"
      );
      return;
    }

    if (!validateFileSize(fileValues)) return;

    let tName;
    const formData = new FormData();
    for (const file of fileValues) {
      // Ffm file size after conversion
      if (!validateFileSize(file)) continue;

      console.log(file.name);
      // Append converted file to FormData
      tName = file.name.slice(0, -4);
      formData.append("files", file);
    }

    const res = await handleFileUploads(formData);

    return { res: res, tam: tName };
  };

  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();
    console.log(fileValues[0]);
    let fileName;
    for (const file of fileValues) {
      // Ffm file size after conversion
      if (!validateFileSize(file)) continue;

      console.log(file.name);
      // Append converted file to FormData
      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 = {
          user_id: user_id,
          url: resulte?.attachments,
          title: type,
          description: description,
          track_name: fileName,
        };
        const res = await CreateTrackAPI(payload);

        const result = await getData();

        if (!res?.error) {
          showToast(globalDispatch, `Track Uploaded`, 5000);
        }
        setLoader(false);
        setIsOpen(false);
      }
    } catch (error) {
      showToast(globalDispatch, `Track 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;
  };

  // const loadFFmpeg = async () => {
  //   setFfmpegLoad(true);
  //   const ffmpegInstance = createFFmpeg({});
  //   console.log('po');
  //   console.log(ffmpegInstance);
  //   await ffmpegInstance.load();
  //   setFfmpeg(ffmpegInstance);
  //   setReady(true);
  //   setFfmpegLoad(false);
  // };

  // const convertVideo = async (file) => {
  //   if (!ffmpeg) return;

  //   ffmpeg.FS('writeFile', 'input.mp4', await fetchFile(file));
  //   await ffmpeg.run(
  //     '-i',
  //     'input.mp4',
  //     '-c:v',
  //     'copy',
  //     '-c:a',
  //     'copy',
  //     '-strict',
  //     '-2', // Disable strict compliance
  //     '-b:v',
  //     '2M', // Set video bitrate to 2 Mbps (medium bitrate)
  //     'output.mp4'
  //   );

  //   const data = ffmpeg.FS('readFile', 'output.mp4');
  //   const blob = new Blob([data.buffer], { type: 'video/mp4' });
  //   return blob;
  // };

  // React.useEffect(() => {
  //   (async function () {
  //     await loadFFmpeg();
  //   })();
  // }, []);

  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-md transform rounded border border-strokedark bg-boxdark transition-all">
        {/* Modal 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">Add Track</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">
            {/* Title Input */}
            <div className="flex flex-col gap-2">
              <label className="text-sm font-medium text-bodydark2">
                Title
              </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 bg-transparent px-4 text-white outline-none placeholder:text-bodydark2"
                  placeholder="Full Routine, Dance Section..."
                />
              </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>

            {/* Audio Upload */}
            <div className="flex flex-col">
              <label className="text-sm font-medium text-bodydark2">
                Audio File
              </label>
              <AudioUpload
                label="Audio"
                isUploading={isUpload}
                setFileValues={setFileValues}
                fileValues={fileValues}
              />
              <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 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 bg-primary px-6 py-2 text-sm font-medium text-white hover:bg-opacity-90"
              disabled={loader || isUploading}
            >
              {loader || isUploading ? (
                <ClipLoader size={16} color="white" />
              ) : (
                "Upload Track"
              )}
            </button>
          </div>
        </div>
      </div>
    </div>
  );
};

export default ClientAddTrackModal;
