"use client";

import { NAV_STATE_KEYS, setNavState } from "@/lib/navigationState";
import { LEARN_SERVE_FORM_PATH, learnServeEditPath } from "@/features/opportunities/routes";
import React from "react";
import moment from "moment";
import { useClock } from "@/hooks/useClock";
import Image from "next/image";
import Link from "next/link";
import { useRouter } from "next/navigation";
import { useTranslation } from "react-i18next";
import Button from "@/components/ui/Button";
import { useLanguageStore } from "@/store/languageStore";
import { useAuthStore } from "@/store/authStore";
import {
  getOpportunityButtonLabelKey,
  getOpportunityButtonState,
  isCreatorRepostState,
  canEditOrDelete,
  isViewerOrganizer,
} from "@/features/shared/opportunityButtonState";
import {
  isOnlineFormat,
  clampText,
  type OpportunityCardProps,
} from "./opportunityCardTypes";
export {
  getOpportunityAccent,
  type OpportunityCardItem,
  type OpportunityAccent,
} from "./opportunityCardTypes";
import OpportunityCardCover from "./OpportunityCardCover";
import { opportunityCardLocation } from "./opportunityCardLocation";
import AssetIcon from "@/components/ui/AssetIcon";
import OpportunityCardTag from "./OpportunityCardTag";

export default function OpportunityCard({
  item,
  isLearnServe = false,
  detailHref,
  borderClass,
  buttonClass,
  peopleIconSrc = "/assets/homepage/person.svg",
  headerOverlay,
  statusPill,
  onTagClick,
  badgePerspective = "viewer",
}: OpportunityCardProps) {
  const { t } = useTranslation();
  const router = useRouter();
  const language = useLanguageStore((state) => state.language);
  const isArabic = language === "ar";
  const user = useAuthStore((state) => state.user);

  const clock = useClock(1000);
  const now = moment(clock);
  const repost = isCreatorRepostState(item, now);
  const isCreator = user?.id != null && isViewerOrganizer(item, user.id);
  const canManage = Boolean(clock) && isCreator && (
    repost ? user?.is_publishing_paused !== true : canEditOrDelete(item, now)
  );
  const buttonState = getOpportunityButtonState({ ...item, opportunity_type: isLearnServe ? "learn_serve_opportunity" : "volunteer_opportunity" }, now);
  const buttonLabelKey = isCreator
    ? repost ? "COMMON.REPOST" : "COMMON.EDIT_TEXT"
    : buttonState === "unregister" && item.is_paid
      ? "COMMON.CARD_REGISTERED_PAID"
      : buttonState === "register" && user?.user_type === "organization"
        ? "COMMON.DETAILS"
        : buttonState === "register" && isLearnServe && item.is_paid ? "COMMON.BOOK" : getOpportunityButtonLabelKey(buttonState);

  const title = (isArabic ? item.title_ar : item.title_en) || "";

  const localized = (
    value?: { value_en?: string | null; value_ar?: string | null } | null
  ) => (isArabic ? value?.value_ar : value?.value_en) ?? "";
  const tag = localized(item.interest_display?.[0]);

  const locationLabel = opportunityCardLocation({
    item,
    isArabic,
    isLearnServe,
    t,
  });

  const rowClass =
    "flex items-center gap-2 leading-tight text-secondary-102 text-sm xss:text-base lg:text-base 2xl:text-lg";

  return (
    <div className="content-card opportunity-card flex h-full flex-col">
      <OpportunityCardCover
        item={item}
        title={title}
        headerOverlay={headerOverlay}
        detailHref={detailHref}
        language={language}
        isLearnServe={isLearnServe}
        badgePerspective={badgePerspective}
        buttonLabelKey={buttonLabelKey}
        now={now}
      />

      <div
        className={`boxshadowsitm relative flex-1 rounded-b-[20px] border border-t-0 bg-[#F7F7F7] px-3 pb-10 xss:px-3 2xl:px-3 ${borderClass}`}
      >
        <Link
          href={detailHref}
          className="absolute inset-0 z-0 rounded-b-[20px]"
        >
          <span className="sr-only">{title}</span>
        </Link>
        <div className="relative z-10">
          <div className="flex items-start justify-between gap-2 pb-1 pt-[19px] 2xl:pb-3">
            <h3 className="flex min-w-0 items-start gap-2 text-lg font-bold text-secondary-100 2xl:text-[20px]">
              <span className="line-clamp-1">{title}</span>
            </h3>
            {statusPill}
          </div>

          <div className="grid grid-cols-2 justify-between pb-[12px] extrasmall:flex-col">
            <div className={rowClass}>
              <Image
                src={
                  isLearnServe
                    ? "/assets/homepage/learn_type.svg"
                    : "/assets/voluneteerevent/age.svg"
                }
                className="h-5 w-5 shrink-0 object-contain"
                width={20}
                height={20}
                unoptimized
                alt=""
                aria-hidden="true"
              />
              <span className="line-clamp-1">
                {isLearnServe ? (
                  clampText(localized(item.learning_type_display), 12)
                ) : (
                  <>
                    {item.from_age}
                    {item.to_age ? <> - {item.to_age}</> : <> +</>}
                  </>
                )}
              </span>
            </div>
            <div className={rowClass}>
              <Image
                src={
                  isOnlineFormat(item)
                    ? "/assets/voluneteerevent/online.svg"
                    : "/assets/homepage/locations.svg"
                }
                className="h-5 w-5 shrink-0 object-contain"
                width={20}
                height={20}
                unoptimized
                alt=""
                aria-hidden="true"
              />
              <span className="line-clamp-1 flex-1 overflow-hidden text-ellipsis">
                {locationLabel}
              </span>
            </div>
          </div>

          <div className="grid grid-cols-2 justify-between extrasmall:flex-col">
            <div className={rowClass}>
              <AssetIcon
                src={peopleIconSrc}
                className="h-5 w-5 shrink-0 object-contain"
              />
              {`${item.registered_volunteers_count ?? 0}/${item.participants_needed ?? 0}`}
            </div>
            <div className={`${rowClass} overflow-hidden`}>
              <AssetIcon
                src="/assets/homepage/health.svg"
                className="h-5 w-5 shrink-0 object-contain"
              />
              <OpportunityCardTag tag={tag} onTagClick={onTagClick} />
            </div>
          </div>
        </div>
      </div>

      <Button
        className={`relative bottom-[25px] mx-auto flex justify-center border-0 ${buttonClass}`}
        variant="primary"
        size="medium"
        onClick={() => {
          // Unavailable actions still let the reader open the opportunity details.
          if (!canManage) { router.push(detailHref); return; }
          const republish = repost;
          setNavState(isLearnServe ? NAV_STATE_KEYS.learnServeForm : NAV_STATE_KEYS.volunteerForm, { id: String(item.id), isRepublish: republish });
          router.push(isLearnServe ? republish ? LEARN_SERVE_FORM_PATH : learnServeEditPath(item.id) : "/volunteer-form");
        }}
      >
        {t(buttonLabelKey)}
      </Button>
    </div>
  );
}
