import React, { useContext, useState } from "react";
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
import AudioPlayer from "Components/AudioPlayer";
import ConfirmModal from "Components/Modal/ConfirmModal";
import AudioPlayer2 from "Components/AudioPlayer2";
import { Download, MoreVertical } from "lucide-react";
import { GlobalContext, showToast } from "Src/globalContext";

const audioFileTypes = ["mp3", "wav", "ogg", "flac", "aac", "wma", "m4a"];

const UploadedAdminInstrumentals2 = ({ uploadedFiles, setDeleteFileId }) => {
  const [activeMenu, setActiveMenu] = useState(null);
  const { dispatch } = useContext(GlobalContext);
  const [localDeleteFileId, setLocalDeleteFileId] = React.useState(null);
  const [showDeleteFileConfirmModal, setShowDeleteFileConfirmModal] =
    React.useState(false);

  const handleDownload = async (url, filename) => {
    try {
      showToast(dispatch, "File Downloading", 3000);
      const response = await fetch(url);
      const blob = await response.blob();
      const blobUrl = window.URL.createObjectURL(blob);

      const link = document.createElement("a");
      link.href = blobUrl;
      link.download = filename;
      document.body.appendChild(link);
      link.click();
      document.body.removeChild(link);
      window.URL.revokeObjectURL(blobUrl);
    } catch (error) {
      console.error("Download failed:", error);
    }
    setActiveMenu(null); // Close menu after download starts
  };

  // Close menu when clicking outside
  React.useEffect(() => {
    const handleClickOutside = () => setActiveMenu(null);
    document.addEventListener("click", handleClickOutside);
    return () => document.removeEventListener("click", handleClickOutside);
  }, []);

  const handleDeleteFileModalClose = () => setShowDeleteFileConfirmModal(false);
  const handleDeleteFileSubmit = () => {
    setDeleteFileId(localDeleteFileId);
    setShowDeleteFileConfirmModal(false);
  };

  return (
    <>
      <div className="flex flex-wrap gap-2">
        {uploadedFiles?.length > 0 &&
          uploadedFiles.map((file, index) => {
            const fileSrc = file.url;
            const fileName = fileSrc.split("/").pop();
            const fileExtension = fileSrc.split(".").pop();
            const isAudio = audioFileTypes.includes(fileExtension);

            return (
              <div
                key={index}
                className="w-[30%] min-w-[230px] rounded border border-stroke bg-boxdark p-2.5 hover:border-primary"
              >
                <div className="flex w-full flex-nowrap items-center gap-2">
                  <div className="flex flex-col items-center gap-2">
                    {/* File Icon & Name */}
                    <div className="flex min-w-0 flex-1 items-center gap-2">
                      <FontAwesomeIcon
                        icon={
                          isAudio ? "fa-solid fa-music" : "fa-solid fa-file"
                        }
                        className="text-sm text-bodydark2"
                      />
                      <a
                        style={{ whiteSpace: "break-spaces" }}
                        href={file.url}
                        rel="noreferrer"
                        target="_blank"
                        className="truncate text-[10px] font-medium text-white hover:text-primary"
                      >
                        {fileName}
                      </a>
                    </div>

                    {/* Audio Player - Compact Version */}
                    {isAudio && (
                      <div className="w-48 flex-shrink-0">
                        <AudioPlayer fileSource={file.url} compact={true} />
                      </div>
                    )}
                  </div>

                  <div className="relative">
                    <button
                      onClick={(e) => {
                        e.stopPropagation();
                        setActiveMenu(activeMenu === index ? null : index);
                      }}
                      className="rounded-full p-1.5 hover:bg-gray-700"
                    >
                      <MoreVertical className="h-4 w-4 text-primary" />
                    </button>

                    {activeMenu === index && (
                      <div className="absolute right-0 z-50 mt-1 w-48 rounded-md bg-boxdark shadow-lg ring-1 ring-black ring-opacity-5">
                        <div className="py-1">
                          <button
                            onClick={(e) => {
                              e.stopPropagation();
                              handleDownload(file.url, fileName);
                            }}
                            className="flex w-full items-center px-4 py-2 text-sm text-white hover:bg-gray-700"
                          >
                            <Download className="mr-2 h-4 w-4" />
                            Download
                          </button>
                          <button
                            onClick={(e) => {
                              e.stopPropagation();
                              setShowDeleteFileConfirmModal(true);
                              setLocalDeleteFileId(file.id);
                            }}
                            className="flex w-full items-center px-4 py-2 text-sm text-danger hover:bg-gray-700"
                          >
                            <FontAwesomeIcon
                              icon="fa-solid fa-trash"
                              className="mr-2 h-4 w-4"
                            />
                            Delete
                          </button>
                        </div>
                      </div>
                    )}
                  </div>
                </div>
              </div>
            );
          })}
      </div>

      {/* Confirm Delete Modal */}
      {showDeleteFileConfirmModal && (
        <ConfirmModal
          confirmText="Are you sure you want to delete this file?"
          setModalClose={handleDeleteFileModalClose}
          setFormYes={handleDeleteFileSubmit}
        />
      )}
    </>
  );
};

export default UploadedAdminInstrumentals2;
