import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
import ClientAddTrackModal from "Components/AddTrackModal";
import SingleTrackRow from "Components/singleTrackRow";
import React from "react";
import { ClipLoader } from "react-spinners";
import { AuthContext, tokenExpireError } from "Src/authContext";
import { getAllTracksAPI } from "Src/services/countTracksService";
import { getAllMembersForManager } from "Src/services/managerServices";
import { getUserDetailsByIdAPI } from "Src/services/userService";
import { createDownloadProgressBox } from "Utils/downloadProgress";
import { GlobalContext } from "../../globalContext";
import CustomSelect2 from "Components/CustomSelect2";

const CountTracksManager = () => {
  const { dispatch: globalDispatch } = React.useContext(GlobalContext);
  const { dispatch } = React.useContext(AuthContext);
  const [isAddVideoModalOpen, setIsAddVideoModalOpen] = React.useState(false);

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

  const [members, setMembers] = React.useState([]);
  const [selectedMemberId, setSelectedMemberId] = React.useState("");
  const [officeEmail, setOfficeEmail] = React.useState("");
  const [UserName, setUserName] = React.useState("");
  const [CompanyName, setCompanyName] = React.useState("");
  const [hasTrackDownloads, setHasTrackDownloads] = React.useState(false);

  const getUserData = async () => {
    try {
      const res = await getUserDetailsByIdAPI(selectedMemberId);
      if (!res.error) {
        setOfficeEmail(res.model?.office_email || "");
        setUserName(res.model.first_name + " " + res.model.last_name);
        setCompanyName(res.model.company_name);
      }
    } catch (error) {}
  };

  const getData = async () => {
    setLoader(true);
    const result = await getAllTracksAPI({ user_id: selectedMemberId });
    setLoader(false);
    if (!result.error) {
      setVideoList(result.list);
    }
  };
  const getAllProducers = async () => {
    try {
      const result = await getAllMembersForManager(
        localStorage.getItem("user")
      );

      if (!result.error) {
        if (result.list.length > 0) {
          let list = result.list;

          list = list.map((row) => {
            row.user_name = row.first_name + " " + row.last_name;
            return { value: row.id, label: row.user_name };
          });

          let forSelect = [];
          if (list.length > 0) {
            list.map((row, i) => {
              forSelect.push({
                value: row.value,
                label: row?.label,
              });
            });
          }

          setMembers(forSelect);
          setSelectedMemberId(forSelect[0]?.value);
        }
      }
    } catch (error) {
      tokenExpireError(dispatch, error.message);
    }
  };

  React.useEffect(() => {
    globalDispatch({
      type: "SETPATH",
      payload: {
        path: "count-tracks",
      },
    });

    (async function () {
      setLoader(true);
      await getAllProducers();
      setLoader(false);
    })();
  }, []);

  React.useEffect(() => {
    if (selectedMemberId) {
      (async function () {
        setLoader(true);
        await getUserData();
        await getData();

        setLoader(false);
      })();
    }
  }, [selectedMemberId]);

  React.useEffect(() => {
    const interval = setInterval(() => {
      if (window.downloadManager?.downloads) {
        const activeTrackDownloads = Array.from(
          window.downloadManager.downloads.values()
        ).some(
          (download) =>
            download.type === "track" && download.status === "downloading"
        );

        setHasTrackDownloads(activeTrackDownloads);
      }
    }, 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
      );
    }
  };

  return (
    <div className="max-w-screen h-full p-4 md:p-4 lg:p-6 xl:p-8">
      {isAddVideoModalOpen && (
        <ClientAddTrackModal
          getData={getData}
          setVideoList={setVideoList}
          setIsOpen={setIsAddVideoModalOpen}
          isOpen={isAddVideoModalOpen}
          user_id={selectedMemberId}
        />
      )}

      <div className="border-strokedark bg-boxdark">
        <div className="px-4 pt-8 2xl:px-9">
          <div className="flex items-center gap-3">
            <h3 className="mb-4 text-2xl font-bold text-white">Count Tracks</h3>
            {hasTrackDownloads && (
              <button
                onClick={showDownloadProgress}
                className="flex items-center gap-2 text-primary hover:text-opacity-90"
              >
                <div className="animate-pulse">
                  <FontAwesomeIcon icon="download" className="h-5 w-5" />
                </div>
              </button>
            )}
          </div>

          {/* Producer Selection */}
          <div className="mb-6">
            <CustomSelect2
              className="w-full rounded-lg border border-strokedark bg-form-input px-5 py-3 outline-none transition focus:border-primary active:border-primary disabled:cursor-default disabled:bg-whiter dark:border-form-strokedark dark:bg-form-input"
              value={selectedMemberId}
              onChange={(value) => setSelectedMemberId(value)}
            >
              <option value="">--Select Producer--</option>
              {members?.map((row, i) => (
                <option key={i} value={row.value}>
                  {row.label}
                </option>
              ))}
            </CustomSelect2>
          </div>
        </div>

        {loader ? (
          <div className="flex h-[calc(100vh-160px)] w-full items-center justify-center">
            <ClipLoader color="#fff" size={30} />
          </div>
        ) : selectedMemberId ? (
          <div className="shadow-default rounded border border-strokedark bg-boxdark dark:border-strokedark dark:bg-boxdark">
            <div className="sm:px-6.5 border-b border-strokedark px-4 py-4 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">
                    {CompanyName}
                  </h4>
                  <span className="text-white dark:text-white">-</span>
                  <div>
                    <span className="font-medium text-white dark:text-white">
                      {UserName}
                    </span>
                    <p className="text-sm text-gray-500 dark:text-gray-400">
                      {officeEmail}
                    </p>
                  </div>
                </div>
                <button
                  onClick={() => setIsAddVideoModalOpen(true)}
                  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"
                >
                  Upload
                </button>
              </div>
            </div>
            <div className="mt-7 w-full overflow-x-auto p-4 shadow md:p-6 2xl:p-10">
              <table className="w-full min-w-[600px]  ">
                <thead className="bg-meta-4 dark:bg-meta-4">
                  <th
                    scope="col"
                    className="px-2 py-3 pl-6 text-left text-xs font-semibold uppercase tracking-wider text-bodydark1"
                  >
                    Title
                  </th>
                  <th
                    scope="col"
                    className="px-2 py-3 text-left text-xs font-semibold uppercase tracking-wider text-bodydark1"
                  >
                    Description
                  </th>
                  <th
                    scope="col"
                    className="px-2 py-3 text-left text-xs font-semibold uppercase tracking-wider text-bodydark1"
                  >
                    Listen
                  </th>
                  <th
                    scope="col"
                    className="px-2 py-3 text-left text-xs font-semibold uppercase tracking-wider text-bodydark1"
                  >
                    Download
                  </th>
                  <th
                    scope="col"
                    className="px-2 py-3 text-left text-xs font-semibold uppercase tracking-wider text-bodydark1"
                  >
                    Delete
                  </th>
                </thead>
                <tbody className="text-white">
                  {loader && (
                    <ClipLoader size={12} color="white" className="py-1" />
                  )}
                  {!loader && videoList.length <= 0 && (
                    <div className="py-1 text-white shadow">
                      No Tracks found!
                    </div>
                  )}

                  {!loader && videoList.length > 0
                    ? videoList.map((video, index) => (
                        <>
                          {" "}
                          <SingleTrackRow
                            key={video.id}
                            video={video}
                            getData={getData}
                          />
                        </>
                      ))
                    : null}
                </tbody>
              </table>
            </div>
          </div>
        ) : null}
      </div>
    </div>
  );
};

export default CountTracksManager;
