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

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

const UploadedSessions = ({
  canUpload = true,
  uploadedFiles,
  setDeleteFileId,
  setEmployeeType,
  setFileUploadType,
  setFormData,
  uploadedFilesProgressData = {},
}) => {
  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);
  }, []);

  return (
    <>
      <div
        onClick={() => {
          setEmployeeType("artist");
          setFileUploadType("session");
        }}
        className="flex flex-col p-6 h-full rounded border border-strokedark bg-boxdark"
      >
        <div className="flex justify-between items-center pb-4 mb-4 border-b border-strokedark">
          <h3 className="text-xl font-semibold text-white">Artist Sessions</h3>
          {canUpload && (
            <span className="text-sm text-bodydark2">
              {uploadedFiles?.length || 0} files uploaded
            </span>
          )}
        </div>

        <div className="overflow-y-auto flex-1 custom-overflow">
          <div className="space-y-4">
            {uploadedFiles?.map((file, index) => {
              const fileName = file.url.split("/").pop();
              const fileExt = fileName.split(".").pop().toLowerCase();
              const isAudio = audioFileTypes.includes(fileExt);

              return (
                <div
                  key={index}
                  className="p-4 rounded border border-strokedark bg-boxdark-2"
                >
                  <div className="flex gap-4 justify-between items-center">
                    <div className="flex-1 min-w-0">
                      <a
                        href={file.url}
                        target="_blank"
                        className="mb-1 w-[85%] truncate text-sm font-medium text-white underline"
                      >
                        {fileName}
                      </a>
                      {isAudio && (
                        <div className="mt-2">
                          <AudioPlayer fileSource={file.url} />
                        </div>
                      )}
                    </div>
                    {canUpload && (
                      <div className="relative">
                        <button
                          onClick={(e) => {
                            e.stopPropagation();
                            setActiveMenu(activeMenu === index ? null : index);
                          }}
                          className="p-2 rounded-full hover:bg-gray-700"
                        >
                          <MoreVertical className="w-5 h-5 text-primary" />
                        </button>

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

        {canUpload && (
          <div className="pt-4 mt-4 border-t border-strokedark">
            <div className="flex flex-col items-center">
              <p className="mb-2 text-sm font-medium text-bodydark2">
                Upload more files
              </p>
              <FileUpload
                uploadedFilesProgressData={uploadedFilesProgressData}
                maxFileSize={2048}
                setFormData={setFormData}
              />
            </div>
          </div>
        )}
      </div>

      {showDeleteFileConfirmModal && (
        <ConfirmModal
          confirmText="Are you sure you want to delete this file?"
          setModalClose={() => setShowDeleteFileConfirmModal(false)}
          setFormYes={() => {
            setDeleteFileId(localDeleteFileId);
            setShowDeleteFileConfirmModal(false);
          }}
        />
      )}
    </>
  );
};

export default UploadedSessions;
