"use client";

import { useEffect, useState } from "react";
import LoadingBar from "react-top-loading-bar";

import { Opportunity } from "@/types/opportunities/opportunity-types";
import { Options } from "@/types/options/options-data-types";
import { parseOpportunity } from "@/utils/opportunities/parse-opportunity";
import Headline from "@/components/pages/participant/opportunities/partials/headline";
import OpportunityCard from "@/components/pages/participant/opportunities/partials/opportunity-card";

type PastOpportunitiesListProps = {
  listOfOpps: Opportunity[];
  options: {
    currencyOptions: Options;
    typeOfStudyOptions: Options;
    paymentMethods: Options;
    jobTopicOptions: Options;
    formatOfResearchOptions: Options;
  };
};

function PastOpportunitiesList({
  listOfOpps,
  options: {
    currencyOptions,
    typeOfStudyOptions,
    paymentMethods,
    jobTopicOptions,
    formatOfResearchOptions,
  },
}: PastOpportunitiesListProps) {
  const [itemsPerPage, setItemsPerPage] = useState(8);
  const [progress, setProgress] = useState(0);

  const increaseItems = () => {
    setItemsPerPage(
      (prevItemsToShow) =>
        prevItemsToShow + (window.innerWidth <= 1024 ? 9 : 18)
    );
  };

  useEffect(() => {
    const handleScroll = () => {
      const scrollPosition =
        window.scrollY || document.documentElement.scrollTop;
      const windowHeight = window.innerHeight;
      const documentHeight = document.documentElement.offsetHeight;

      // This threshold value is required for mobile and tablets, otherwise the user will have to scroll until the bottom of the page, past footer.
      const threshold = window.innerWidth <= 1024 ? 500 : 1000;

      if (window.innerWidth <= 1024) {
        if (windowHeight + scrollPosition >= documentHeight - threshold) {
          setProgress(50);
          increaseItems();
          setProgress(100);
        }
      } else {
        if (windowHeight + scrollPosition >= documentHeight) {
          setProgress(50);
          increaseItems();
          setProgress(100);
        }
      }
    };

    window.addEventListener("scroll", handleScroll);
    window.addEventListener("touchmove", handleScroll);
    return () => {
      window.removeEventListener("scroll", handleScroll);
      window.removeEventListener("touchmove", handleScroll);
    };
  }, []);

  return (
    <div className="w-full min-h-screen py-8 bg-participant-light dark:bg-participant-dark">
      <Headline isPastOpps />
      <span className="flex justify-center lg:justify-end pe-8 font-inter font-medium text-xs text-black/40 dark:text-white/60">{`Showing ${
        listOfOpps.length
      } ${
        listOfOpps.length === 1
          ? "expired opportunity"
          : "expired opportunities"
      }.`}</span>
      <div className="flex flex-row items-center justify-center xl:items-start xl:justify-between py-6 xl:ms-8">
        <div className="flex flex-col xl:w-full">
          <div className="grid grid-cols-1 justify-center items-center m-auto md:grid-cols-2 lg:grid-cols-3 xxxl:grid-cols-4 2xxl:grid-cols-5 xl:pe-6 xxl:pe-24 gap-4 place-items-center h-full mx-12 lg:mx-0">
            {listOfOpps.slice(0, itemsPerPage).map((item, index) => {
              const parsedOpportunity = parseOpportunity(
                item,
                currencyOptions,
                typeOfStudyOptions,
                paymentMethods,
                jobTopicOptions,
                formatOfResearchOptions
              );

              return (
                <OpportunityCard
                  key={`${item}-${index}`}
                  isPastOpps
                  currencyOptions={currencyOptions}
                  opportunityDetail={parsedOpportunity}
                  onClickCard={() => null}
                />
              );
            })}
          </div>
        </div>
      </div>
      <LoadingBar
        className="bg-participant-bittersweet dark:bg-participant-cerulean"
        height={4}
        progress={progress}
        onLoaderFinished={() => setProgress(0)}
      />
    </div>
  );
}

export default PastOpportunitiesList;
