import AudioPlayer from "Components/audioPlayerModal";
import { GlobalContext } from "Src/globalContext";
import { createDownloadProgressBox } from "Utils/downloadProgress";
import { Download, Play } from "lucide-react";
import React from "react";

const ClientSingleTrack = ({ track }) => {
  const [play, setPlay] = React.useState(false);
  const { dispatch: globalDispatch } = React.useContext(GlobalContext);

  function downloadFile(urle, track_name) {
    const url = urle ? JSON.parse(urle)[0] : "";
    console.log(url, track_name);
    const fileName = `${track_name}.${url?.split(".").pop()}`;

    // Initialize download manager
    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", // Specify track type
    });

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

    fetch(url)
      .then((response) => {
        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
        );

        // Remove completed download after a delay
        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);
        window.downloadManager.downloads.set(downloadId, {
          fileName,
          progress: 0,
          status: "failed",
          type: "track",
        });
        window.downloadManager.progressBox.updateDownloads(
          window.downloadManager.downloads
        );
      });
  }

  return (
    <>
      {play && (
        <AudioPlayer
          fileSource={track.url ? JSON.parse(track?.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">{track.title}</td>
        <td className="px-4 py-4">{track.description}</td>
        <td className="px-4 py-4">
          <Play
            className="h-6 w-6 cursor-pointer hover:text-primary"
            onClick={() => setPlay(true)}
          />
        </td>
        <td className="px-4 py-4">
          <Download
            className="h-6 w-6 cursor-pointer hover:text-primary"
            onClick={() => downloadFile(track.url, track.track_name)}
          />
        </td>
      </tr>
    </>
  );
};

export default ClientSingleTrack;
