import { Play, Download, Trash } from "lucide-react";
import React from "react";
import ConfirmModal from "Components/Modal/ConfirmModal";
import { GlobalContext, showToast } from "Src/globalContext";
import AudioPlayer from "./audioPlayerModal";
import { deleteTrackAPI } from "Src/services/countTracksService";
import DuoConfirmModal from "./Modal/DuoConfirmModal";
import { createDownloadProgressBox } from "Utils/downloadProgress";

const SingleTrackRow = ({ video, getData }) => {
  const [showRealDeleteWorkOrderModal, setShowRealDeleteWorkOrderModal] =
    React.useState(false);
  const [showDeleteVideoModal, setShowDeleteVideoModal] = React.useState(false);
  const [play, setPlay] = React.useState(false);
  const { dispatch: globalDispatch } = React.useContext(GlobalContext);

  const handleRealDeleteWorkOrderModalClose = () => {
    setShowRealDeleteWorkOrderModal(false);
  };

  const openSecondDelete = () => {
    setShowRealDeleteWorkOrderModal(false);
    setTimeout(() => {
      setShowDeleteVideoModal(true);
    }, 500);
  };

  const handleDeleteVideo = async (id) => {
    await deleteTrackAPI(id);
    setShowDeleteVideoModal(false);
    await getData();
    showToast(globalDispatch, `Track Deleted`, 5000);
  };

  const url = video?.url ? JSON.parse(video?.url) : " ";

  function downloadFile() {
    const url = video?.url ? JSON.parse(video?.url)[0] : "";

    const fileName = `${video?.title}.${url?.split(".").pop()}`;
    console.log(url, fileName);

    console.log(fileName);

    // Add this download to the global downloads list
    window.downloadManager = window.downloadManager || {
      downloads: new Map(),
      progressBox: null,
    };

    // Create progress box if it doesn't exist
    if (!window.downloadManager.progressBox) {
      window.downloadManager.progressBox = createDownloadProgressBox();
    }

    // Add this download to the list
    const downloadId = Date.now();
    window.downloadManager.downloads.set(downloadId, {
      fileName,
      progress: 0,
      status: "starting",
      type: "track",
    });

    // Update UI
    window.downloadManager.progressBox.updateDownloads(
      window.downloadManager.downloads
    );

    fetch(url)
      .then((response) => {
        if (!response.ok) throw new Error("Download failed");
        const contentLength = response.headers.get("content-length");
        const reader = response.body.getReader();
        let receivedLength = 0;

        return new ReadableStream({
          start(controller) {
            function push() {
              reader.read().then(({ done, value }) => {
                if (done) {
                  controller.close();
                  return;
                }

                receivedLength += value.length;
                const progress = (receivedLength / contentLength) * 100;

                // Update progress
                window.downloadManager.downloads.set(downloadId, {
                  fileName,
                  progress: Math.round(progress),
                  status: "downloading",
                  type: "track",
                });
                window.downloadManager.progressBox.updateDownloads(
                  window.downloadManager.downloads
                );

                controller.enqueue(value);
                push();
              });
            }
            push();
          },
        });
      })
      .then((stream) => new Response(stream))
      .then((response) => response.blob())
      .then((blob) => {
        const url = window.URL.createObjectURL(blob);
        const a = document.createElement("a");
        a.href = url;
        a.download = fileName;
        document.body.appendChild(a);
        a.click();
        document.body.removeChild(a);
        window.URL.revokeObjectURL(url);

        // Update status to complete
        window.downloadManager.downloads.set(downloadId, {
          fileName,
          progress: 100,
          status: "complete",
          type: "track",
        });
        window.downloadManager.progressBox.updateDownloads(
          window.downloadManager.downloads
        );

        setTimeout(() => {
          window.downloadManager.downloads.delete(downloadId);
          if (window.downloadManager.downloads.size === 0) {
            window.downloadManager.progressBox.remove();
            window.downloadManager.progressBox = null;
          } else {
            window.downloadManager.progressBox.updateDownloads(
              window.downloadManager.downloads
            );
          }
        }, 2000);
      })
      .catch((error) => console.error("Error downloading file:", error));
  }

  return (
    <>
      {showRealDeleteWorkOrderModal && (
        <ConfirmModal
          confirmText={`Are you sure you want to delete this track?`}
          setModalClose={handleRealDeleteWorkOrderModalClose}
          setFormYes={openSecondDelete}
        />
      )}

      {showDeleteVideoModal && (
        <DuoConfirmModal
          confirmText={`Are you sure you want to delete this track? This action cannot be undone.`}
          setModalClose={setShowDeleteVideoModal}
          setFormYes={() => handleDeleteVideo(video.id)}
        />
      )}

      {play && <AudioPlayer fileSource={url[0]} setModalClose={setPlay} />}

      <tr className="border-b border-strokedark text-bodydark1 hover:bg-primary/5">
        <td className="px-4 py-4 text-white xl:pl-6 2xl:pl-9">
          {video?.title}
        </td>
        <td className="px-4 py-4">{video?.description}</td>
        <td className="px-4 py-4">
          <Play
            className="t h-6 w-6 cursor-pointer hover:text-primary"
            onClick={() => setPlay(true)}
          />
        </td>
        <td className="px-4 py-4">
          <Download
            className="t h-6 w-6 cursor-pointer hover:text-primary"
            onClick={downloadFile}
          />
        </td>
        <td className="px-4 py-4">
          <Trash
            className="t h-6 w-6 cursor-pointer hover:text-primary"
            onClick={() => {
              setShowRealDeleteWorkOrderModal(true);
            }}
          />
        </td>
      </tr>
    </>
  );
};

export default SingleTrackRow;
