import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
import { AuthContext } from "Src/authContext";
import { GlobalContext, showToast } from "Src/globalContext";
import { retrieveAllMediaAPI } from "Src/services/clientProjectDetailsService";
import { createDownloadProgressBox } from "Utils/downloadProgress";
import React, { useState } from "react";
import { useParams } from "react-router";
import { ClipLoader } from "react-spinners";
import ClientAddVideoModal from "../ClientAddVideoModal";
import MusicSection from "../musicSection";
import SingleVideoRow from "./singleVideoRow";

const ClientMediaTabs = ({ viewModel }) => {
  const projectId = useParams();
  const { dispatch, state: authState } = React.useContext(AuthContext);
  const [isAddVideoModalOpen, setIsAddVideoModalOpen] = React.useState(false);
  const { dispatch: globalDispatch } = React.useContext(GlobalContext);

  const [videoList, setVideoList] = React.useState([]);

  const [loader, setLoader] = useState(true);

  const [pageCount, setPageCount] = React.useState(0);
  const [dataTotal, setDataTotal] = React.useState(0);
  const [currentPage, setPage] = React.useState(0);
  const [canPreviousPage, setCanPreviousPage] = React.useState(false);
  const [canNextPage, setCanNextPage] = React.useState(false);

  const [ffmpegLoad, setFfmpegLoad] = React.useState(false);

  const [hasVideoDownloads, setHasVideoDownloads] = React.useState(false);
  const [hasMusicDownloads, setHasMusicDownloads] = React.useState(false);

  console.log(hasVideoDownloads, hasMusicDownloads);

  const getData = async (page, limit) => {
    const result = await retrieveAllMediaAPI({
      page: page,
      limit: limit,
      filter: {
        project_id: projectId.id,
      },
    });

    if (!result.error) {
      const { list, total, limit, num_pages, page } = result;
      const filter = list.filter((elem) => elem.is_music === 0);
      setVideoList(filter);
      // setPageSize(limit);
      setPageCount(num_pages);
      setPage(page);
      setDataTotal(total);
      setCanPreviousPage(page > 1);
      setCanNextPage(page + 1 <= num_pages);
    }

    setLoader(false);
  };

  React.useEffect(() => {
    getData(1, 2000);
    //  getMusicAndLIcense();
  }, []);
  console.log(window.downloadManager?.downloads);
  React.useEffect(() => {
    const interval = setInterval(() => {
      if (window.downloadManager?.downloads) {
        // Check for video downloads
        const activeVideoDownloads = Array.from(
          window.downloadManager.downloads.values()
        ).some((download) => download.type === "video");

        // Check for music downloads
        const activeMusicDownloads = Array.from(
          window.downloadManager.downloads.values()
        ).some((download) => download.type === "music");

        setHasVideoDownloads(activeVideoDownloads);
        setHasMusicDownloads(activeMusicDownloads);
      }
    }, 1000);

    return () => clearInterval(interval);
  }, []);

  const showDownloadProgress = () => {
    console.log("Current download manager:", window.downloadManager);
    console.log("Downloads size:", window.downloadManager?.downloads.size);
    console.log("Progress box:", window.downloadManager?.progressBox);

    if (window.downloadManager) {
      // Always create new progress box if it doesn't exist
      if (!window.downloadManager.progressBox) {
        console.log("Creating new progress box");
        window.downloadManager.progressBox = createDownloadProgressBox();
      }

      console.log("Showing progress box");
      window.downloadManager.progressBox.show();
      window.downloadManager.progressBox.updateDownloads(
        window.downloadManager.downloads
      );
    }
  };

  function isSameDay(date1, date2) {
    // Get the routine submission date and convert it to a Date object
    let routineDate = new Date(viewModel?.routine_submission_date);

    // Create a new Date object for the "next day" by adding 1 day to the routineDate
    let nextDayUTC = new Date(
      Date.UTC(
        routineDate.getUTCFullYear(),
        routineDate.getUTCMonth(),
        routineDate.getUTCDate() + 1
      )
    );

    // Set the time to midnight UTC
    nextDayUTC.setUTCHours(0, 0, 0, 0);
    let timezoneOffset = nextDayUTC.getTimezoneOffset() * 60000;

    // Apply the timezone offset to the next day to align it with the local time
    let nextDayLocal = new Date(nextDayUTC.getTime() + timezoneOffset);

    // Get the current time in local time
    let currentTimeLocal = new Date();

    // Log the dates for debugging
    console.log("Next Day (Local):", nextDayLocal);
    console.log("Current Local Time:", currentTimeLocal);

    // Compare the current local time with the next day (adjusted to local time)
    return currentTimeLocal > nextDayLocal;
  }

  return (
    <div className="max-w-screen h-full p-4 md:p-4 lg:p-0">
      {isAddVideoModalOpen && (
        <ClientAddVideoModal
          setVideoList={setVideoList}
          setIsOpen={setIsAddVideoModalOpen}
          isOpen={isAddVideoModalOpen}
          ffmpegLoad={ffmpegLoad}
          setFfmpegLoad={setFfmpegLoad}
        />
      )}

      <div className="border-strokedark bg-boxdark">
        <div className="shadow-default rounded border border-strokedark bg-boxdark dark:border-strokedark dark:bg-boxdark">
          <div className="border-b border-strokedark px-4 py-4 2xl:px-9 dark:border-strokedark">
            <div className="flex w-full items-center justify-between">
              <div className="flex items-center gap-3">
                <h4 className="text-lg font-semibold text-white dark:text-white">
                  Videos
                </h4>
              </div>

              <div className="flex items-center gap-3">
                {hasVideoDownloads && (
                  <button
                    onClick={showDownloadProgress}
                    className="inline-flex items-center justify-center text-primary hover:text-primary/80"
                  >
                    <FontAwesomeIcon icon="download" className="h-5 w-5" />
                  </button>
                )}

                <button
                  className={`inline-flex items-center justify-center rounded-md bg-primary px-6 py-2.5 text-center font-medium text-white hover:bg-opacity-90 ${
                    isSameDay(
                      new Date(),
                      new Date(viewModel?.routine_submission_date)
                    ) &&
                    authState?.role === "client" &&
                    "opacity-50"
                  }`}
                  onClick={(e) => {
                    if (
                      isSameDay(
                        new Date(),
                        new Date(viewModel?.routine_submission_date)
                      ) &&
                      authState?.role === "client"
                    ) {
                      showToast(
                        globalDispatch,
                        "Email the producer office to unlock the team details",
                        7000
                      );
                    } else {
                      setIsAddVideoModalOpen(true);
                    }
                  }}
                >
                  Upload
                </button>
              </div>
            </div>
          </div>

          <div className="p-4 md:p-6 2xl:p-10">
            <div className="max-h-[380px] overflow-y-auto">
              <table className="w-full table-auto">
                <thead className="bg-meta-4">
                  <tr>
                    <th className="px-4 py-3 text-left text-xs font-medium uppercase tracking-wider text-bodydark1 2xl:pl-9">
                      Date
                    </th>
                    <th className="px-4 py-3 text-left text-xs font-medium uppercase tracking-wider text-bodydark1">
                      Type
                    </th>
                    <th className="px-4 py-3 text-left text-xs font-medium uppercase tracking-wider text-bodydark1">
                      Description
                    </th>
                    <th className="px-4 py-3 text-left text-xs font-medium uppercase tracking-wider text-bodydark1">
                      Actions
                    </th>
                  </tr>
                </thead>
                <tbody className="text-white">
                  {loader ? (
                    <tr>
                      <td colSpan="6" className="text-center">
                        <div className="flex items-center justify-start gap-3 px-8 py-6 text-center">
                          <ClipLoader size={20} color="white" />
                          <span className="animate-pulse text-xl font-semibold text-white ease-out">
                            Loading Videos...
                          </span>
                        </div>
                      </td>
                    </tr>
                  ) : videoList.length === 0 ? (
                    <tr>
                      <td colSpan="6">
                        <div className="p-4 text-center text-white">
                          No videos found!
                        </div>
                      </td>
                    </tr>
                  ) : (
                    videoList.map((video) => (
                      <SingleVideoRow
                        key={video.id}
                        video={video}
                        viewModel={viewModel}
                        getData={getData}
                      />
                    ))
                  )}
                </tbody>
              </table>
            </div>
          </div>
        </div>

        {/* Keep existing MusicSection component */}
        <MusicSection viewModel={viewModel} hasDownloads={hasMusicDownloads} />
      </div>
    </div>
  );
};

export default ClientMediaTabs;
