"use client";

import { useRouter } from "next/navigation";
import { useMutation } from "@tanstack/react-query";
import { useTranslation } from "react-i18next";
import { toast } from "sonner";

import { Button } from "@/components/ui/Button";
import { registerForLearnServeOpportunity } from "@/features/opportunities/services/learnServe";
import { registerWithConflictCheck } from "@/features/opportunities/scheduleConflict";
import {
  ABANDONED_CHECKOUT_TTL_HOURS,
  checkoutFromRegistration,
  formatAmount,
  goToCheckout,
  isPaidRegistrationResponse,
} from "@/features/opportunities/payment";
import { getApiErrorMessage, isApiSuccess, isBanRefusal } from "@/lib/api/errors";
import { NAV_STATE_KEYS, setNavState } from "@/lib/navigationState";
import { useLanguageStore } from "@/store/languageStore";

export interface LearnServeRegistrationDetails {
  title_ar?: string;
  title_en?: string;
  start_date?: string;
  isInPerson?: boolean;
  /** BE-125 — drives the payment notice and the button's wording. */
  isPaid?: boolean;
  price?: number | string | null;
  /** The opportunity's own WhatsApp contact, for the «تم تسجيلك» page. */
  whatsapp_link?: string | null;
}

interface ConfirmRegistrationModalProps {
  opportunityId: string;
  setOpenForm: () => void;
  refetch: () => void;
  opportunityDetails: LearnServeRegistrationDetails;
}

/** Registration confirmation for a learn & serve opportunity without time slots. */
export default function ConfirmRegistrationModal({
  opportunityId,
  setOpenForm,
  refetch,
  opportunityDetails,
}: ConfirmRegistrationModalProps) {
  const { t } = useTranslation();
  const isPaid = opportunityDetails.isPaid === true;
  /* `null` when the opportunity is paid but carries no price — the notice
     still shows, without a figure it cannot vouch for. */
  const amount = isPaid ? formatAmount(opportunityDetails.price) : null;
  // PDF p.3: amounts in «د.ك» / KD, never the raw ISO code.
  const amountDue = amount === null ? null : `${amount} ${t("COMMON.KWD_SHORT")}`;
  const router = useRouter();
  const selectedLanguage = useLanguageStore((s) => s.language);

  const registerMutation = useMutation({
    mutationFn: registerForLearnServeOpportunity,
  });

  const handleConfirm = async () => {
    if (!opportunityId) return;
    try {
      const response = await registerWithConflictCheck((extra) =>
        registerMutation.mutateAsync({ opportunity_id: opportunityId, ...extra })
      );
      // Kept the registration that clashes: nothing to register.
      if (response === null) {
        setOpenForm();
        return;
      }

      // The API also rejects with HTTP 200 + `key: "fail"`, so the envelope —
      // not the status — decides, and its `msg` carries the reason.
      if (!isApiSuccess(response)) {
        toast.error(
          getApiErrorMessage(
            response,
            selectedLanguage,
            t("COMMON.TOAST.REGISTRATION_FAILED")
          )
        );
        return;
      }

      /*
       * BE-125 — a paid opportunity answers with a checkout to go to, and the
       * seat is already held. Reporting «registered» and routing to the
       * thank-you page, which is what this did, left the payer believing they
       * were in while the gateway was never opened.
       */
      const checkout = checkoutFromRegistration(response);
      if (checkout) {
        toast.success(t("COMMON.TOAST.REDIRECTING_TO_PAYMENT"));
        setOpenForm();
        goToCheckout(checkout.gateway_checkout_url as string);
        return;
      }

      /* The paid branch with no URL: the gateway refused to start. Not a
         success, and not something to send to the thank-you page either. */
      if (isPaidRegistrationResponse(response)) {
        toast.error(t("COMMON.TOAST.CHECKOUT_UNAVAILABLE"));
        setOpenForm();
        refetch();
        return;
      }

      // A16: «تم تسجيلك بنجاح» + in-app notice; the account-signup string asks to check the email.
      toast.success(t("COMMON.YOU_ARE_REGISTERED"));
      setNavState(NAV_STATE_KEYS.opportunityThankyou, {
        ...opportunityDetails,
        islearnserve: true,
      });
      setOpenForm();
      refetch();
      router.push("/register-now");
    } catch (error) {
      // The ban popup already explains the refusal (PDF p.43).
      if (isBanRefusal(error)) {
        setOpenForm();
        return;
      }
      toast.error(
        getApiErrorMessage(
          error,
          selectedLanguage,
          t("COMMON.TOAST.REGISTRATION_FAILED")
        )
      );
    }
  };

  return (
    <div className="md:w-[100%] rounded-lg bg-white filtermodal">
      <h2 className="text-center text-lg pb-5">
        {t("COMMON.ARE_YOU_SURE_REGISTER_LEARNSHARE_OPPORTUNITY")}
      </h2>

      {/* BE-125 — said before the click, not after: confirming reserves the
          seat and leaves the site for the gateway. */}
      {isPaid && (
        <div className="mx-auto mb-8 max-w-[520px] rounded-2xl bg-[#29246D08] p-4 text-center text-sm text-secondary-102">
          <p>
            {t("COMMON.PAYMENT_REQUIRED_NOTICE", {
              hours: ABANDONED_CHECKOUT_TTL_HOURS,
            })}
          </p>
          {amountDue && (
            <p className="mt-2 text-base font-bold text-primary-5">
              {t("COMMON.AMOUNT_DUE")}: {amountDue}
            </p>
          )}
        </div>
      )}
      <p className="mb-5 text-center text-sm leading-relaxed text-secondary-102">{t("COMMON.REGISTERED_NAME_CERTIFICATE_NOTICE")}</p>
      <div className="flex flex-wrap xss:flex-col justify-center w-full gap-3">
        <Button
          variant="primary"
          type="button"
          size="medium"
          onClick={handleConfirm}
          disabled={registerMutation.isPending}
          className="!w-auto !px-6 whitespace-nowrap xss:!w-full"
        >
          {isPaid ? t("COMMON.CONTINUE_TO_PAYMENT") : t("COMMON.CONFIRM")}
        </Button>
        <Button
          variant="secondary"
          size="medium"
          type="button"
          onClick={() => setOpenForm()}
          disabled={registerMutation.isPending}
          className="xss:!w-full"
        >
          {t("COMMON.CANCEL")}
        </Button>
      </div>
    </div>
  );
}
