import ConfirmModal from "Components/Modal/ConfirmModal";
import { GlobalContext, showToast } from "Src/globalContext";
import { deleteMediaAPI } from "Src/services/clientProjectDetailsService";
import { createDownloadProgressBox } from "Utils/downloadProgress";
import { Download, Trash, MoreVertical } from "lucide-react";
import moment from "moment";
import React from "react";
import { createPopper } from "@popperjs/core";

const SingleMusicRow = ({ music, getData, viewModel }) => {
  const { dispatch: globalDispatch } = React.useContext(GlobalContext);
  const [showDeleteMusicModal, setShowDeleteMusicModal] = React.useState(false);
  const [showOptionsMenu, setShowOptionsMenu] = React.useState(false);

  const buttonRef = React.useRef(null);
  const popperRef = React.useRef(null);
  const [popperInstance, setPopperInstance] = React.useState(null);

  React.useEffect(() => {
    if (buttonRef.current && popperRef.current) {
      const instance = createPopper(buttonRef.current, popperRef.current, {
        placement: "bottom-end",
        modifiers: [
          {
            name: "offset",
            options: {
              offset: [0, 8],
            },
          },
          {
            name: "preventOverflow",
            options: {
              padding: 8,
            },
          },
        ],
      });
      setPopperInstance(instance);
      return () => instance.destroy();
    }
  }, [showOptionsMenu]);

  // Close dropdown when clicking outside
  React.useEffect(() => {
    const handleClickOutside = (event) => {
      if (
        showOptionsMenu &&
        buttonRef.current &&
        !buttonRef.current.contains(event.target) &&
        popperRef.current &&
        !popperRef.current.contains(event.target)
      ) {
        setShowOptionsMenu(false);
      }
    };

    document.addEventListener("mousedown", handleClickOutside);
    return () => document.removeEventListener("mousedown", handleClickOutside);
  }, [showOptionsMenu]);

  const handleDeleteMusic = async () => {
    await deleteMediaAPI(music.id);
    setShowDeleteMusicModal(false);
    await getData();
    showToast(globalDispatch, `Music Deleted`, 5000);
  };

  function downloadFile() {
    const url = music?.url ? JSON.parse(music?.url)[0] : "";
    const fileName = `${viewModel?.program_name}_${viewModel?.team_name}_${
      music?.type
    }_${moment.utc(music.update_at).local().format("MM-DD-YYYY")}.${url
      ?.split(".")
      .pop()}`;

    // 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: "music", // Specify music 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: "music",
                });
                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: "music",
        });
        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: "music",
        });
        window.downloadManager.progressBox.updateDownloads(
          window.downloadManager.downloads
        );
      });
  }
  const formatDate = (dateString) => {
    // Split the dateString into day, month, and year parts

    const [year, month, day] = dateString?.split("-");

    // Create a new Date object with the provided year, month (subtract 1 because months are zero-indexed), and day
    const date = new Date(`${year}-${month}-${day}`);

    // Check if the date is valid
    if (isNaN(date.getTime())) {
      return null; // Return null if the date is invalid
    }

    // Format month to have leading zero if necessary
    const formattedMonth = (date.getMonth() + 1).toString().padStart(2, "0");

    // Format day to have leading zero if necessary
    const formattedDay = date.getDate().toString().padStart(2, "0");

    // Get the year portion
    const formattedYear = date.getFullYear();

    const formattedDate = `${formattedMonth}/${formattedDay}/${formattedYear}`;

    return formattedDate;
  };

  console.log(music.type);
  return (
    <>
      {showDeleteMusicModal ? (
        <ConfirmModal
          confirmText={`Are you sure you want to delete this ${music?.type}?`}
          setModalClose={setShowDeleteMusicModal}
          setFormYes={() => {
            handleDeleteMusic();
          }}
        />
      ) : null}
      <tr className="border-b border-b-strokedark">
        <td className="whitespace-nowrap px-3 py-4">
          {moment.utc(music.update_at).local().format("MM-DD-YYYY")}
        </td>
        <td className="px-3 py-4">{music?.type}</td>
        <td style={{ wordBreak: "break-word" }} className="px-3 py-4">
          {music?.description}
        </td>
        <td className="px-3 py-4">
          <div className="flex items-center gap-2">
            <button
              onClick={downloadFile}
              className="inline-flex h-8 w-8 items-center justify-center rounded-md border border-strokedark text-white transition hover:border-primary hover:bg-primary/10"
            >
              <Download className="h-4 w-4" />
            </button>

            <button
              ref={buttonRef}
              onClick={() => setShowOptionsMenu(!showOptionsMenu)}
              className="inline-flex h-8 w-8 items-center justify-center rounded-md border border-strokedark text-white transition hover:border-primary hover:bg-primary/10"
            >
              <MoreVertical className="h-4 w-4" />
            </button>

            {showOptionsMenu && (
              <div
                ref={popperRef}
                className="z-50 w-20 rounded-md border border-strokedark bg-boxdark shadow-lg"
              >
                <div className="py-1">
                  <button
                    onClick={() => {
                      setShowDeleteMusicModal(true);
                      setShowOptionsMenu(false);
                    }}
                    className="flex w-full items-center gap-2 px-4 py-2 text-left text-sm text-red-500 hover:bg-primary/10"
                  >
                    <Trash className="h-4 w-4" />
                  </button>
                </div>
              </div>
            )}
          </div>
        </td>
      </tr>
    </>
  );
};

export default SingleMusicRow;
