import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
import { AuthContext } from "Src/authContext";
import { GlobalContext } 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 SingleVideoRow from "./singleVideoRow";

const VideoSection = ({
  viewModel,
  video_ids = null,
  setVideo_ids = null,
  projectID = null,
  edit_complete = false,
  hasDownloads,
}) => {
  const params = useParams();
  const projectId = projectID || params?.id;
  console.log(projectId);

  const [isAddVideoModalOpen, setIsAddVideoModalOpen] = React.useState(false);

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

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

  const [showDeleteVideoModal, setShowDeleteVideoModal] = useState(false);
  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 getData = async (page, limit) => {
    const result = await retrieveAllMediaAPI({
      page: page,
      limit: limit,
      filter: {
        project_id: projectId,
      },
    });

    if (!result.error) {
      const { list, total, 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);
  };

  console.log("dreyyyyy");

  React.useEffect(() => {
    getData(1, 2000);
    //  getMusicAndLIcense();
  }, []);

  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
      );
    }
  };

  return (
    <div className="bg-boxdark">
      {isAddVideoModalOpen && (
        <ClientAddVideoModal
          projectIDVIDEO={projectId}
          setVideoList={setVideoList}
          setIsOpen={setIsAddVideoModalOpen}
          isOpen={isAddVideoModalOpen}
          video_ids={video_ids}
          setVideo_ids={setVideo_ids}
        />
      )}

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

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

              {!edit_complete && (
                <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 ${
                    edit_complete && "opacity-50"
                  }`}
                  onClick={() => !edit_complete && setIsAddVideoModalOpen(true)}
                >
                  Upload
                </button>
              )}
            </div>
          </div>
        </div>

        <div className="p-4 md:p-6 2xl:p-10">
          <div className="custom-overflow 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-xs font-medium tracking-wider text-left uppercase text-bodydark1 2xl:pl-9">
                    Date
                  </th>
                  <th className="px-4 py-3 text-xs font-medium tracking-wider text-left uppercase text-bodydark1">
                    Type
                  </th>
                  <th className="px-4 py-3 text-xs font-medium tracking-wider text-left uppercase text-bodydark1">
                    Description
                  </th>
                  <th className="px-4 py-3 text-xs font-medium tracking-wider text-left uppercase text-bodydark1">
                    Actions
                  </th>
                </tr>
              </thead>
              <tbody className="text-white">
                {loader ? (
                  <tr>
                    <td colSpan="6" className="text-center">
                      <div className="flex gap-3 justify-start items-center px-8 py-6 text-center">
                        <ClipLoader size={20} color="white" />
                        <span className="text-xl font-semibold text-white ease-out animate-pulse">
                          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}
                      showDeleteVideoModal={showDeleteVideoModal}
                      getData={getData}
                      setShowDeleteVideoModal={setShowDeleteVideoModal}
                    />
                  ))
                )}
              </tbody>
            </table>
          </div>
        </div>
      </div>
    </div>
  );
};

export default VideoSection;
