"use client";

import Image from "next/image";
import { useRouter } from "next/navigation";
import { FaChevronRight } from "react-icons/fa6";
import {
  Card,
  CardBody,
  CardFooter,
  CardHeader,
  Chip,
} from "@nextui-org/react";
import React, { useMemo } from "react";
import useSWR from "swr";
import { parse } from "date-fns";

import Button from "@/components/common/button";
import { INTERNAL_PAGES } from "@/constants/pages-mapping/internal-pages-mapping";
import { formatIncentives } from "@/utils/format-incentive";
import { truncateText } from "@/utils/text-utils";
import { getOpportunitiesNotLoggedIn } from "@/services/opportunities";
import { parseOpportunity } from "@/utils/opportunities/parse-opportunity";
import { Options } from "@/types/options/options-data-types";
import PFRSamLogo from "@/components/common/sprites/pfr-sam-logo-sprite";
import { FRIENDLY_TOPICS_ICONS } from "@/utils/opportunities/job-topic-icons";
import type { ParticipantHomeContent } from "@/lib/participant-home-ghost-content";

type OpportunitiesShowcaseProps = {
  content: ParticipantHomeContent["opportunities"];
  options: {
    currencyOptions: Options;
    typeOfStudyOptions: Options;
    paymentMethods: Options;
    jobTopicOptions: Options;
    formatOfResearchOptions: Options;
  };
};

const fetchOpportunities = async () => {
  const sort: { colId: string; sort: "desc" | "asc" } = {
    colId: "publishDate",
    sort: "desc",
  };

  const filterModel = {};
  const itemsPerPage = 3;
  const currentPage = 1;

  const opportunities = await getOpportunitiesNotLoggedIn(
    itemsPerPage,
    currentPage,
    sort,
    filterModel,
  );
  return opportunities;
};

function OpportunitiesShowcase({
  content,
  options,
}: OpportunitiesShowcaseProps) {
  const router = useRouter();

  const cleanHTML = (html: string) => {
    return html.replace(/<[^>]*>/g, " ");
  };

  const handleExploreOpportunitiesClick = () => {
    router.push(INTERNAL_PAGES.participant.opportunities.main);
  };

  const handleOnClickCard = (jobId: number) => {
    router.push(`${INTERNAL_PAGES.participant.opportunities.main}/${jobId}`);
  };

  const { data, isLoading, error } = useSWR(
    "opportunities",
    fetchOpportunities,
  );

  const {
    currencyOptions,
    typeOfStudyOptions,
    paymentMethods,
    jobTopicOptions,
    formatOfResearchOptions,
  } = options;

  const parsedOpportunities = useMemo(() => {
    const recentOpps = data?.data || [];

    return recentOpps
      ?.map((opportunity) => {
        return parseOpportunity(
          opportunity,
          currencyOptions,
          typeOfStudyOptions,
          paymentMethods,
          jobTopicOptions,
          formatOfResearchOptions,
        );
      })
      .sort((a, b) => {
        const dateA = parse(
          a.jobInformation.endDate,
          "dd/MM/yyyy",
          new Date(),
        ).getTime();
        const dateB = parse(
          b.jobInformation.endDate,
          "dd/MM/yyyy",
          new Date(),
        ).getTime();
        return dateB - dateA;
      });
  }, [
    data,
    currencyOptions,
    typeOfStudyOptions,
    paymentMethods,
    jobTopicOptions,
    formatOfResearchOptions,
  ]);

  return (
    <div className="mx-auto lg:max-w-none py-24 px-6 lg:px-16 xxl:px-20 xxxl:px-24 flex flex-col xl:flex-row bg-participant-light dark:bg-participant-dark w-full">
      <div className="xl:w-1/2 xxl:w-2/5 xxxl:w-1/3">
        <span className="text-center font-noto text-sm font-medium tracking-widest uppercase">
          {content.eyebrow}
        </span>
        <h2 className="text-3xl font-black sm:text-5xl xxl:text-6xl xxxl:text-7xl font-inter mt-2">
          {content.heading}
        </h2>
        <p className="text-lg xxl:text-xl leading-8 xxl:leading-9 text-gray-800 dark:text-gray-200 font-noto w-full lg:max-w-xl mt-4 xxl:mt-6 xxxl:mt-8">
          {content.lead}
        </p>
        <div className="pe-12 mt-12 xxl:mt-16 xxxl:mt-20 m-auto">
          <Button
            fullWidth
            btnLabel="Explore all opportunities"
            customVariant="primary"
            endContent={<FaChevronRight />}
            onClick={handleExploreOpportunitiesClick}
          />
        </div>
      </div>
      <div className="grid grid-cols-1 gap-4 xxl:gap-6 xxxl:gap-8 mx-auto mt-12 xl:mt-0 xl:w-1/2">
        {isLoading && (
          <div className="flex flex-col items-center justify-center">
            <PFRSamLogo animate width={50} />
            <span className="text-sm">
              Loading our most recent research opportunities...
            </span>
          </div>
        )}
        {error && (
          <div className="flex flex-col items-center justify-center">
            <PFRSamLogo width={50} />
            <span className="text-sm text-red-500">
              Failed to load opportunities. Please try again later.
            </span>
          </div>
        )}
        {parsedOpportunities?.map((opportunity) => {
          const {
            description,
            jobId,
            title,
            jobTopic,
            incentives,
            typeOfStudy,
            thumbnail,
            altTextThumbnail,
          } = opportunity;

          const cleanDescription = truncateText(cleanHTML(description), 100);

          return (
            <Card
              key={jobId}
              isHoverable
              isPressable
              className="bg-white border border-gray-200 dark:border-white/10 h-64 sm:h-52 lg:h-48 xxl:h-56 xxxl:h-64 rounded-lg hover:bg-white/80 hover:dark:bg-[#39393e] shadow-none max-w-2xl xxl:max-w-4xl xxxl:max-w-6xl hover:cursor-pointer grid grid-cols-3 gap-2 dark:bg-[#18181a]"
              onPress={() => handleOnClickCard(jobId)}
            >
              <div className="col-span-1 w-full rounded-none h-full p-0">
                <Image
                  aria-hidden
                  alt={altTextThumbnail || ""}
                  className="object-cover w-[400px] rounded-none h-64 sm:h-52 lg:h-48 xxl:h-56 xxxl:h-64"
                  height={400}
                  loading="eager"
                  src={`data:image/png;base64,${thumbnail}` || ""}
                  width={400}
                />
              </div>
              <div className="col-span-2 my-auto">
                <CardHeader className="text-start flex flex-col items-start space-y-1 xxl:space-y-2 xxxl:space-y-3">
                  <Chip
                    classNames={{
                      content: "font-semibold py-1",
                      base: "bg-slate-200 dark:bg-slate-700 text-black dark:text-white font-inter font-extrabold text-xs",
                    }}
                    startContent={
                      FRIENDLY_TOPICS_ICONS[
                        jobTopic as keyof typeof FRIENDLY_TOPICS_ICONS
                      ] &&
                      React.createElement(
                        FRIENDLY_TOPICS_ICONS[
                          jobTopic as keyof typeof FRIENDLY_TOPICS_ICONS
                        ],
                        { className: "mx-1" },
                      )
                    }
                  >
                    {jobTopic}
                  </Chip>
                  <span className="font-inter font-bold text-black dark:text-white text-sm xxl:text-base xxxl:text-lg py-1">
                    {truncateText(title, 100)}
                  </span>
                </CardHeader>
                <CardBody className="py-0">
                  <p className="font-noto text-gray-700 dark:text-gray-300 text-sm xxl:text-base xxxl:text-lg">
                    {cleanDescription}
                  </p>
                </CardBody>
                <CardFooter className="text-sm xxl:text-base xxxl:text-lg font-bold font-inter text-gray-900 dark:text-gray-300">
                  <div className="inline-flex space-x-1 items-center">
                    <span>{formatIncentives(incentives, currencyOptions)}</span>
                    <span>
                      {incentives.length > 2 ? " + other currencies" : ""}
                    </span>
                  </div>
                  <span className="inline mx-2 h-4 w-px bg-slate-300"></span>
                  <span>{typeOfStudy.join(", ")}</span>
                </CardFooter>
              </div>
            </Card>
          );
        })}
      </div>
    </div>
  );
}

export default OpportunitiesShowcase;
