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 from "react";
import { useParams } from "react-router";
import { ClipLoader } from "react-spinners";
import ClientAddMusicModal from "./ClientAddMusicModal";
import SingleMusicRow from "./ClientViewProjectDetails/singleMusicRow";

const MusicSection = ({
  viewModel,
  hasDownloads,
  music_ids = null,
  setMusic_ids = null,
  projectID = null,
  edit_complete = false,
}) => {
  const { dispatch, state: authState } = React.useContext(AuthContext);
  const params = useParams();
  const projectId = projectID || params?.id;
  const { dispatch: globalDispatch } = React.useContext(GlobalContext);

  const [musicList, setMusicList] = React.useState([]);
  const [isAddMusicModalOpen, setIsAddMusicModalOpen] = React.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 [loading, setLoading] = React.useState(false);

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

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

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

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

    setLoader(false);
  };

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

  // function updatePageSize(limit) {
  //   getMusicAndLIcense(currentPage, limit);
  // }

  // function previousPage() {
  //   getMusicAndLIcense(currentPage - 1, pageSize);
  // }

  // function nextPage() {
  //   getMusicAndLIcense(currentPage + 1, pageSize);
  // });

  function isSameDay(date1, date2) {
    // Get the routine submission date and convert it to a Date object
    console.log(viewModel);
    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="mt-8 bg-boxdark">
      <div className="shadow-default rounded-sm bg-boxdark 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-start justify-between">
            <div className="flex items-start">
              <div>
                <h3 className="mb-1 text-lg font-bold text-white">
                  License and Music
                </h3>

                <div className="mt-[4px]">
                  <span className="text-sm font-medium text-white dark:text-white">
                    Download Mixes and Documents
                  </span>
                </div>
              </div>
            </div>

            <div className="flex items-center gap-3">
              {hasDownloads && (
                <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>
              )}

              {(authState?.role === "member" ||
                authState?.role === "manager" ||
                authState?.role === "admin") && (
                <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"
                  } ${
                    isSameDay(
                      new Date(),
                      new Date(viewModel?.routine_submission_date)
                    ) &&
                    authState?.role === "client" &&
                    !projectID &&
                    "opacity-50"
                  }`}
                  onClick={() => {
                    if (
                      isSameDay(
                        new Date(),
                        new Date(viewModel?.routine_submission_date)
                      ) &&
                      authState?.role === "client" &&
                      !projectID
                    ) {
                      showToast(
                        globalDispatch,
                        "Email the producer office to unlock the team details",
                        7000
                      );
                    } else if (edit_complete) {
                      return;
                    } else {
                      setIsAddMusicModalOpen(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-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="divide-y divide-strokedark text-white">
                {loader ? (
                  <tr>
                    <td colSpan="5" 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 Music...
                        </span>
                      </div>
                    </td>
                  </tr>
                ) : musicList.length === 0 ? (
                  <tr>
                    <td colSpan="5">
                      <div className="p-4 text-center text-white">
                        No Music/License found!
                      </div>
                    </td>
                  </tr>
                ) : (
                  musicList.map((music, index) => (
                    <SingleMusicRow
                      key={index}
                      music={music}
                      viewModel={viewModel}
                      getData={getMusicAndLIcense}
                    />
                  ))
                )}
              </tbody>
            </table>
          </div>
        </div>
      </div>

      {isAddMusicModalOpen && (
        <ClientAddMusicModal
          setMusicList={setMusicList}
          setIsOpen={setIsAddMusicModalOpen}
          isOpen={isAddMusicModalOpen}
          music_ids={music_ids}
          setMusic_ids={setMusic_ids}
        />
      )}
    </div>
  );
};

export default MusicSection;
