import React from "react";
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
import AudioPlayer from "Components/AudioPlayer";
import ConfirmModal from "Components/Modal/ConfirmModal";
import JSZip from "jszip";
import UploadedFiles from "../ProducerWorkOrder/UploadedFiles";
import { GlobalContext, showToast } from "Src/globalContext";
import moment from "moment";
import { Download } from "lucide-react";

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

const UploadedSessionFiles = ({
  code,
  canUpload = true,
  uploadedFiles,
  setDeleteFileId,
}) => {
  const { dispatch: globalDispatch } = React.useContext(GlobalContext);
  const [localDeleteFileId, setLocalDeleteFileId] = React.useState(null);
  const [showDeleteFileConfirmModal, setShowDeleteFileConfirmModal] =
    React.useState(false);

  const handleDeleteFileModalClose = () => {
    setShowDeleteFileConfirmModal(false);
  };

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

  async function handleDownload() {
    const zip = new JSZip();
    const workOrderFolder = zip.folder(
      `WorkOrder_${code}_artist_session_files_${moment().format(
        "HH:mm:ss_DD-MM-YYYY"
      )}`
    );
    const artistSessionsFolder = workOrderFolder.folder("Artist_Sessions");

    const promises = uploadedFiles.map(async (row) => {
      const url = row.url;
      const fileName = url.split("/").pop();

      try {
        showToast(globalDispatch, "File download has started", 5000);
        const response = await fetch(url);
        if (response.ok) {
          const blob = await response.blob();
          artistSessionsFolder.file(fileName, blob);
        } else {
          console.error("Error fetching file:", response.statusText);
        }
      } catch (error) {
        showToast(globalDispatch, error.message, 5000, "error");
        console.error("Error fetching file:", error);
      }
    });

    await Promise.all(promises);

    zip.generateAsync({ type: "blob" }).then((content) => {
      const zipLink = document.createElement("a");
      zipLink.href = URL.createObjectURL(content);
      zipLink.download = `WorkOrder_${code}_artist_session_files_${moment().format(
        "HH:mm:ss_DD-MM-YYYY"
      )}.zip`;
      zipLink.click();
    });
  }

  console.log(uploadedFiles);

  return (
    <>
      <div className="mt-4 flex w-full max-w-5xl flex-row flex-wrap justify-between">
        <h5 className="text-md items-center font-semibold text-white">
          Session Files Uploaded by the Artist
        </h5>
        {uploadedFiles && uploadedFiles.length > 0 && (
          <button
            onClick={handleDownload}
            className="rounded bg-primary px-4 py-2 font-bold text-white hover:bg-primary/90"
          >
            Download All
          </button>
        )}
      </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>
                  <Download
                    onClick={() => {
                      const link = document.createElement("a");
                      link.href = fileSrc;
                      link.download = fileSrcTemp;
                      document.body.appendChild(link);
                      link.click();
                      document.body.removeChild(link);
                    }}
                    className="h-5 w-5 text-primary"
                  />
                </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>
                )}
                {canUpload && (
                  <button
                    onClick={(e) => {
                      e.stopPropagation();
                      setShowDeleteFileConfirmModal(true);
                      setLocalDeleteFileId(file.id);
                    }}
                    className="group rounded-full p-2 hover:bg-danger/5"
                  >
                    <FontAwesomeIcon
                      icon="fa-solid fa-trash"
                      className="h-4 w-4 text-danger group-hover:text-danger/90"
                    />
                  </button>
                )}
              </div>
            </div>
          );
        })
      ) : (
        <div className="text-white">No session files uploaded yet.</div>
      )}

      {showDeleteFileConfirmModal ? (
        <ConfirmModal
          confirmText={`Are you sure you want to delete this file?`}
          setModalClose={handleDeleteFileModalClose}
          setFormYes={handleDeleteFileSubmit}
        />
      ) : null}
    </>
  );
};

export default UploadedSessionFiles;
