"use client";

import Image from "next/image";
import {
  Card,
  CardBody,
  CardFooter,
  CardHeader,
  Chip,
  Tooltip,
} from "@nextui-org/react";
import {
  FaCalendar,
  FaCheck,
  FaClock,
  FaComputer,
  FaLocationDot,
  FaStar,
} from "react-icons/fa6";
import React, { JSX } from "react";

import { ParsedOpportunity } from "@/types/opportunities/opportunity-types";
import { formatIncentives } from "@/utils/format-incentive";
import { truncateText } from "@/utils/text-utils";
import { Options } from "@/types/options/options-data-types";
import { formatDateRange } from "@/components/pages/participant/opportunities/other-utils";
import { FRIENDLY_TOPICS_ICONS } from "@/utils/opportunities/job-topic-icons";

function CardLabel({ text, icon }: { text: string; icon?: JSX.Element }) {
  return (
    <span className="absolute top-2 left-0 bg-white text-black px-3 py-1 text-xs z-10 font-inter font-semibold flex items-center gap-1">
      {icon && icon}
      {text}
    </span>
  );
}

function DescriptionItem({
  icon,
  text,
  tooltipContent,
}: {
  icon: JSX.Element;
  text: string;
  tooltipContent: string;
}) {
  return (
    <Tooltip
      className="p-1.5 text-xs rounded-full text-black dark:text-white"
      content={tooltipContent}
      delay={1000}
    >
      <div className="flex space-x-1 items-center">
        <span className="text-black dark:text-white">{icon}</span>
        <p className="text-black dark:text-white">{text}</p>
      </div>
    </Tooltip>
  );
}

type OpportunityCardProps = {
  opportunityDetail: ParsedOpportunity;
  currencyOptions: Options;
  isPastOpps?: boolean;
  onClickCard: (jobId: number) => void;
};

function OpportunityCard({
  opportunityDetail,
  currencyOptions,
  isPastOpps,
  onClickCard,
}: OpportunityCardProps) {
  const {
    jobId,
    durationText,
    startDate,
    thumbnail,
    altTextThumbnail,
    isFeatured,
    jobTopic,
    title,
    blurb,
    location,
    description,
    typeOfStudy,
    hasApplied,
    incentives,
    hideLocation,
    jobInformation,
  } = opportunityDetail;

  const { endDate } = jobInformation;

  const dateRange = formatDateRange("short", startDate, endDate, true);
  const fullDateRange = formatDateRange("long", startDate, endDate, false);
  const formattedStart =
    typeof dateRange === "string" ? dateRange : dateRange.formattedStart;
  const formattedEnd =
    typeof dateRange === "string" ? dateRange : dateRange.formattedEnd;

  const cities =
    (location !== null &&
      location.split(/,|&/).map((location) => location.trim())) ||
    [];

  const displayCity =
    !location || hideLocation
      ? "To be confirmed"
      : cities.length > 1
      ? "Multiple locations"
      : cities[0];

  const cleanDescription = description.replace(/<[^>]*>/g, " ").trim();

  const truncatedDescription =
    cleanDescription.length > 125
      ? truncateText(cleanDescription, 125)
      : cleanDescription;

  const blurbToUse =
    blurb && blurb.trim() !== "" ? blurb : truncatedDescription;

  return (
    <Card
      disableAnimation
      className={`shadow-none border border-gray-200 dark:border-white/10 bg-white dark:bg-[#18181a] relative ${
        !isPastOpps ? "w-[320px] lg:w-[350px] h-[520px]" : ""
      } flex flex-col light rounded-md ${
        isPastOpps ? "cursor-not-allowed" : "cursor-pointer"
      } pb-4 hover:bg-gray-100 hover:dark:bg-[#39393e]`}
      isPressable={!isPastOpps}
      onPress={() => onClickCard(jobId)}
    >
      {!isPastOpps && (
        <CardHeader className="p-0">
          <Image
            aria-hidden
            alt={altTextThumbnail || ""}
            className={`object-cover w-[360px] rounded-none h-[176px] ${
              isPastOpps ? "filter grayscale" : ""
            }`}
            height={176}
            loading="eager"
            src={`data:image/png;base64,${thumbnail}` || ""}
            width={360}
          />
          {isFeatured && !isPastOpps && !hasApplied && (
            <CardLabel icon={<FaStar />} text="Featured" />
          )}
          {isPastOpps && <CardLabel text="Expired" />}
          {hasApplied && !isPastOpps && (
            <CardLabel icon={<FaCheck />} text="Applied" />
          )}
        </CardHeader>
      )}
      <CardBody className="p-4 flex flex-col space-y-2">
        <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-sm h-10 text-black dark:text-white">
          {title.length > 75 ? truncateText(title, 75) : title}
        </span>
        <div className="inline-flex space-x-1 items-center">
          <span className="font-inter font-black text-3xl xl:text-start text-black dark:text-white">
            {formatIncentives(incentives, currencyOptions)}
          </span>
          <span className="text-xs font-normal ps-1 text-gray-700 dark:text-gray-300">
            {incentives.length > 2 ? " + other currencies available" : ""}
          </span>
        </div>
        <p
          className={`${
            !isPastOpps
              ? "font-noto text-gray-700 dark:text-gray-300 text-sm h-20"
              : "font-noto text-gray-700 dark:text-gray-300 text-sm"
          }`}
        >
          {blurbToUse}
        </p>
      </CardBody>
      <CardFooter className="p-4 flex flex-col space-y-2 pt-4 font-inter font-bold text-xs justify-start items-start">
        <DescriptionItem
          icon={<FaCalendar className="size-3" />}
          text={formattedStart + " - " + formattedEnd || "-"}
          tooltipContent={`${fullDateRange}.`}
        />
        <DescriptionItem
          icon={<FaClock className="size-3" />}
          text={
            durationText
              ? (durationText.trimEnd().endsWith(".")
                  ? durationText.trimEnd().slice(0, -1)
                  : durationText
                ).slice(0, 45) + (durationText.length > 45 ? "..." : "")
              : "-"
          }
          tooltipContent="The duration of this opportunity."
        />
        <DescriptionItem
          icon={<FaLocationDot className="size-3" />}
          text={displayCity || "-"}
          tooltipContent="The city and country where this opportunity takes place."
        />
        <DescriptionItem
          icon={<FaComputer className="size-3" />}
          text={typeOfStudy?.length ? typeOfStudy.join(", ") : "-"}
          tooltipContent="The type(s) of study of this opportunity."
        />
      </CardFooter>
    </Card>
  );
}

export default OpportunityCard;
