import React, { useState } from "react";
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
import { useFileUpload } from "Src/libs/uploadFileHook";
import { ClipLoader } from "react-spinners";
import UploadProgressBar from "Src/libs/uploadProgressBar";
import MkdSDK from "Utils/MkdSDK";
import { Trash, X } from "lucide-react";
import { deleteOneFileAPI } from "Src/services/projectService";
import { deleteS3FileAPI } from "Src/services/workOrderService";
import { GlobalContext, showToast } from "Src/globalContext";

const FileUploadModal = ({
  isOpen,
  setIsOpen,
  type,
  songId,
  currentFiles,
  onUpload,
  callDataAgain,
}) => {
  const { dispatch: globalDispatch } = React.useContext(GlobalContext);
  const [files, setFiles] = useState([]);
  const [dragActive, setDragActive] = useState(false);
  const [isUploading, setIsUploading] = useState(false);
  console.log(currentFiles, "currentfoi");
  const {
    uploadFiles: uploadFilesAPI,
    progress,
    error,
    isUploading: uploading,
  } = useFileUpload();

  console.log(currentFiles);

  const handleDrag = (e) => {
    e.preventDefault();
    e.stopPropagation();
    if (e.type === "dragenter" || e.type === "dragover") {
      setDragActive(true);
    } else if (e.type === "dragleave") {
      setDragActive(false);
    }
  };

  const handleDrop = (e) => {
    e.preventDefault();
    e.stopPropagation();
    setDragActive(false);
    if (e.dataTransfer.files && e.dataTransfer.files[0]) {
      setFiles(Array.from(e.dataTransfer.files));
    }
  };

  const handleFileChange = (e) => {
    if (e.target.files && e.target.files[0]) {
      setFiles(Array.from(e.target.files));
    }
  };

  const handleUpload = async () => {
    if (files.length === 0) return;

    try {
      setIsUploading(true);
      const sdk = new MkdSDK();

      // Create FormData and upload files
      const formData = new FormData();
      for (const file of files) {
        formData.append("files", file);
      }

      const uploadResult = await uploadFilesAPI(formData);

      if (!uploadResult.error) {
        // Upload file data to the work order
        await sdk.callRawAPI(
          "/v3/api/custom/equality_record/work_order/public/upload_files_data",
          {
            project_id: 0,
            subproject_id: songId,
            workorder_id: 0,
            employee_id: null, // This should be set based on the type (writer/engineer)
            employee_type: type === "instrumental" ? "writer" : "engineer",
            type: type,
            attachments: uploadResult.attachments,
            is_from_admin: 1,
          },
          "POST"
        );

        // Call the onUpload callback with the result
        if (onUpload) {
          onUpload(uploadResult.attachments);
        }

        setIsOpen(false);
      }
    } catch (error) {
      console.error("Error uploading files:", error);
    } finally {
      setIsUploading(false);
    }
  };

  const handleDeleteFileSubmit = async (id) => {
    try {
      const result = await deleteOneFileAPI(id);
      if (!result.error) {
        if (result.file) {
          const s3delRes = await deleteS3FileAPI(result.file.url);
          if (!s3delRes.error) {
            showToast(globalDispatch, result.message, 5000);
            callDataAgain();
          }
        }
      } else {
        showToast(globalDispatch, result.message, 5000, "error");
      }
    } catch (error) {
      showToast(globalDispatch, error.message, 5000, "error");
    }
  };

  console.log(currentFiles, "current");
  return (
    <div className="fixed inset-0 z-50 flex items-center justify-center bg-black bg-opacity-50">
      <div className="w-full max-w-md rounded-lg bg-boxdark p-6">
        <div className="mb-4 flex items-center justify-between">
          <h3 className="text-lg font-medium">
            Upload {type === "instrumental" ? "Instrumental" : "Master"} Files
          </h3>
          <button onClick={() => setIsOpen(false)}>
            <X />
          </button>
        </div>

        {/* Current Files */}
        {currentFiles && (
          <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 currentFiles === "string" ? (
                <div className="flex items-center gap-2">
                  <FontAwesomeIcon icon="fa-solid fa-file-audio" />
                  <span>{currentFiles}</span>
                </div>
              ) : (
                currentFiles?.map((file, i) => (
                  <div
                    key={i}
                    className="mb-2 flex items-center justify-between gap-2"
                  >
                    <div 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>
                    <button
                      onClick={() => handleDeleteFileSubmit(file.id)}
                      className="text-red-500 hover:text-red-600"
                      title="Delete file"
                    >
                      <Trash />
                    </button>
                  </div>
                ))
              )}
            </div>
          </div>
        )}

        {/* Upload Area */}
        <div
          className={`relative flex min-h-[200px] cursor-pointer flex-col items-center justify-center rounded-lg border-2 border-dashed border-gray-600 bg-boxdark-2 p-6 transition-colors ${
            dragActive ? "border-primary" : ""
          }`}
          onDragEnter={handleDrag}
          onDragLeave={handleDrag}
          onDragOver={handleDrag}
          onDrop={handleDrop}
        >
          <input
            type="file"
            multiple
            className="absolute inset-0 cursor-pointer opacity-0"
            onChange={handleFileChange}
          />
          <FontAwesomeIcon
            icon="fa-solid fa-cloud-upload"
            className="mb-4 h-10 w-10 text-gray-400"
          />
          <p className="text-center text-sm">
            Drag & drop files here or click to select
          </p>
        </div>

        {/* Selected Files */}
        {files.length > 0 && (
          <div className="mt-4">
            <h4 className="mb-2 text-sm font-medium">Selected Files:</h4>
            <div className="rounded bg-boxdark-2 p-2">
              {files.map((file, i) => (
                <div key={i} className="flex items-center gap-2">
                  <FontAwesomeIcon icon="fa-solid fa-file-audio" />
                  <span>{file.name}</span>
                </div>
              ))}
            </div>
          </div>
        )}

        {/* Upload Progress */}
        {isUploading && (
          <div className="mt-4">
            <UploadProgressBar progress={progress} isUploading={uploading} />
          </div>
        )}

        {/* Actions */}
        <div className="mt-6 flex justify-end gap-3">
          <button
            className="rounded bg-gray-600 px-4 py-2 text-sm hover:bg-gray-700"
            onClick={() => setIsOpen(false)}
            disabled={isUploading}
          >
            Cancel
          </button>
          <button
            className="flex items-center gap-2 rounded bg-primary px-4 py-2 text-sm hover:bg-primary/80"
            onClick={handleUpload}
            disabled={files.length === 0 || isUploading}
          >
            {isUploading ? (
              <>
                <ClipLoader size={16} color="white" />
                <span>Uploading...</span>
              </>
            ) : (
              "Upload"
            )}
          </button>
        </div>
      </div>
    </div>
  );
};

export default FileUploadModal;
