"use client";

import { Suspense, useState } from "react";
import { usePathname, useSearchParams } from "next/navigation";
import { useQuery } from "@tanstack/react-query";
import { useTranslation } from "react-i18next";
import { isAxiosError } from "axios";

import Loader from "@/components/ui/Loader";
import Button from "@/components/ui/Button";
import ButtonLink from "@/components/ui/ButtonLink";
import { getApiErrorMessage } from "@/lib/api/errors";
import { useAuthStore } from "@/store/authStore";
import { useLanguageStore } from "@/store/languageStore";
import { useSessionReady } from "@/store/useSessionReady";
import { verifyPayment } from "../services/learnServe";
import { goToCheckout } from "../payment";
import {
  PAYMENT_POLL_INTERVAL_MS,
  paymentReferenceFromQuery,
  paymentReturnState,
  resumableCheckoutUrl,
  shouldPollPayment,
  paymentReturnTitleKey,
} from "../paymentReturn";

/**
 * Upay's return page; the state and the wording always come from our API
 * (`payment_status`, `outcome`), never from Upay's query or from which of the
 * two return URLs (`/payment/result`, `/payment/cancelled`) the payer landed on.
 */
function PaymentReturnContent() {
  const { t } = useTranslation();
  const query = useSearchParams();
  const pathname = usePathname();
  const user = useAuthStore((s) => s.user);
  const language = useLanguageStore((s) => s.language);
  const sessionReady = useSessionReady();
  const reference = paymentReferenceFromQuery(query);
  const [attempts, setAttempts] = useState(0);
  const status = useQuery({
    queryKey: ["payment-verify", reference, user?.id, language],
    queryFn: async () => {
      setAttempts((n) => n + 1);
      return verifyPayment(reference as string);
    },
    enabled: sessionReady && Boolean(user && reference),
    retry: false,
    refetchInterval: (q) => (shouldPollPayment(paymentReturnState(q.state.data?.data), attempts) ? PAYMENT_POLL_INTERVAL_MS : false),
  });

  if (!sessionReady) return <Loader />;
  if (!reference) return <Panel title={t("COMMON.PAYMENT_REFERENCE_MISSING")} />;
  if (!user) {
    const returnTo = `${pathname}?${query.toString()}`;
    return (
      <Panel title={t("COMMON.PAYMENT_LOGIN_REQUIRED")}>
        <ButtonLink href={`/login?returnTo=${encodeURIComponent(returnTo)}`}>{t("COMMON.LOGIN")}</ButtonLink>
      </Panel>
    );
  }
  if (status.isLoading) return <Panel title={t("COMMON.PAYMENT_CHECKING")} busy />;
  if (status.isError) {
    return (
      <Panel title={isAxiosError(status.error) && status.error.response?.status === 404 ? t("COMMON.PAYMENT_PAYER_ACCOUNT_REQUIRED") : getApiErrorMessage(status.error, language) || t("COMMON.PAYMENT_VERIFY_FAILED")}>
        <Button onClick={() => { void status.refetch(); }}>{t("COMMON.RETRY")}</Button>
      </Panel>
    );
  }

  const record = status.data?.data;
  const state = paymentReturnState(record) ?? "unpaid";
  const checkoutUrl = state === "pending" || state === "unpaid" ? resumableCheckoutUrl(record) : null;
  const polling = shouldPollPayment(state, attempts);
  const title = t(paymentReturnTitleKey(state, polling, record?.outcome));
  const detail = state === "unpaid" || state === "refunding" || state === "refunded" ? record?.outcome_message : null;

  return (
    <Panel title={title} detail={detail?.trim() === title.trim() ? null : detail} busy={polling}>
      {checkoutUrl && <Button onClick={() => goToCheckout(checkoutUrl)}>{t("COMMON.CONTINUE_TO_PAYMENT")}</Button>}
      {record?.opportunity_id ? (
        <ButtonLink variant="secondary" href={`/learn-share-event-detail/${record.opportunity_id}`}>{t("COMMON.PAYMENT_VIEW_COURSE")}</ButtonLink>
      ) : (
        <ButtonLink variant="secondary" href="/">{t("COMMON.HOME")}</ButtonLink>
      )}
    </Panel>
  );
}

function Panel({ title, detail, busy, children }: { title: string; detail?: string | null; busy?: boolean; children?: React.ReactNode }) {
  return (
    <section role="status" aria-live="polite" aria-busy={busy || undefined} className="mx-auto my-16 flex max-w-lg flex-col items-center gap-4 rounded-2xl border border-gray-200 bg-white px-6 py-10 text-center">
      <h1 className="text-xl font-bold text-gray-900">{title}</h1>
      {detail && <p className="text-sm text-gray-600">{detail}</p>}
      {busy && <Loader />}
      {children && <div className="flex flex-wrap justify-center gap-3">{children}</div>}
    </section>
  );
}

export default function PaymentReturn() {
  return (
    <Suspense fallback={<Loader />}>
      <PaymentReturnContent />
    </Suspense>
  );
}
