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

const SingleVideoRow = ({
  video,

  getData,

  viewModel,
}) => {
  const { dispatch: globalDispatch } = React.useContext(GlobalContext);
  const [play, setPlay] = React.useState(false);
  const [showDeleteVideoModal, setShowDeleteVideoModal] = 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 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;
  };

  const handleDeleteVideo = async () => {
    await deleteMediaAPI(video.id);
    setShowDeleteVideoModal(false);
    await getData();
    showToast(globalDispatch, `Video Deleted`, 5000);
  };

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

  console.log(url);
  function downloadFile() {
    const url = video?.url ? JSON.parse(video?.url)[0] : "";
    const fileName = `${viewModel?.program_name}_${viewModel?.team_name}_${
      video?.type
    }_${moment.utc(video.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: "video",
    });

    // 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: "video",
                });
                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: "video",
        });
        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);
        // Update status to failed
        window.downloadManager.downloads.set(downloadId, {
          fileName,
          progress: 0,
          status: "failed",
          type: "video",
        });
        window.downloadManager.progressBox.updateDownloads(
          window.downloadManager.downloads
        );
      });
  }

  console.log(video.type);
  return (
    <>
      {showDeleteVideoModal && (
        <ConfirmModal
          confirmText={`Are you sure you want to delete ${
            video?.type ? video?.type : "video"
          }`}
          setModalClose={() => setShowDeleteVideoModal(false)}
          setFormYes={handleDeleteVideo}
        />
      )}
      {play && <VideoPlayer fileSource={url[0]} setModalClose={setPlay} />}
      <tr className="h border-b border-strokedark text-bodydark1">
        <td className="whitespace-nowrap px-4 py-4 text-white xl:pl-6 2xl:pl-9">
          {moment.utc(video.update_at).local().format("MM-DD-YYYY")}
        </td>
        <td className="px-4 py-4">{video?.type}</td>
        <td className="px-4 py-4">{video?.description}</td>
        <td className="px-4 py-4">
          <div className="flex items-center gap-2">
            <button
              onClick={() => setPlay(true)}
              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"
            >
              <Play className="h-4 w-4" />
            </button>

            <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 cursor-pointer 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={() => {
                      setShowDeleteVideoModal(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 SingleVideoRow;
