import React, { useContext, useState } from "react";
import AudioPlayer from "Components/AudioPlayer";
import { MoreVertical, Download } from "lucide-react";
import { GlobalContext, showToast } from "Src/globalContext";

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

const AdminInstrumentals = ({ uploadedFiles }) => {
  const [activeMenu, setActiveMenu] = useState(null);
  const { dispatch } = useContext(GlobalContext);

  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);
  }, []);

  return (
    <div>
      <div className="mt-6 flex w-full max-w-5xl flex-row flex-wrap justify-between"></div>

      {uploadedFiles &&
        uploadedFiles.length > 0 &&
        uploadedFiles.map((file, index) => {
          let fileSrc = `${file.url}`;
          let fileSrcTemp = fileSrc.split("/").pop();
          let fileExtension = fileSrc.split(".").pop();
          return (
            <div key={index} className="mb-4 flex flex-col gap-1">
              {audioFileTypes.includes(fileExtension) && (
                <div className="flex items-center gap-3">
                  <a
                    className="truncate text-sm text-white underline"
                    href={fileSrc}
                    rel="noreferrer"
                    target="_blank"
                  >
                    {fileSrcTemp}
                  </a>
                  <div className="relative">
                    <button
                      onClick={(e) => {
                        e.stopPropagation();
                        setActiveMenu(activeMenu === index ? null : index);
                      }}
                      className="rounded-full p-1 hover:bg-gray-700"
                    >
                      <MoreVertical className="h-5 w-5 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(fileSrc, fileSrcTemp);
                            }}
                            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>
                        </div>
                      </div>
                    )}
                  </div>
                </div>
              )}

              <div className="flex flex-row items-center gap-4">
                {audioFileTypes.includes(fileExtension) && (
                  <AudioPlayer fileSource={fileSrc} />
                )}
                {!audioFileTypes.includes(fileExtension) && (
                  <a
                    className="truncate text-sm text-white underline"
                    href={fileSrc}
                    rel="noreferrer"
                    target="_blank"
                  >
                    {fileSrcTemp}
                  </a>
                )}
              </div>
            </div>
          );
        })}
    </div>
  );
};

export default AdminInstrumentals;
