import Link from "next/link";
import { finalizeStripeCheckout } from "@/lib/stripe-fulfillment";

export default async function CheckoutSuccessPage({
  searchParams,
}: {
  searchParams: Promise<{ session_id?: string }>;
}) {
  const { session_id } = await searchParams;
  let result: Awaited<ReturnType<typeof finalizeStripeCheckout>> | null = null;
  if (session_id) {
    try {
      result = await finalizeStripeCheckout(session_id);
      console.log("[CHECKOUT SUCCESS] result:", JSON.stringify(result));
    } catch (e) {
      console.error("[CHECKOUT SUCCESS] error:", e);
    }
  }
  const invoiceName =
    result && "invoiceName" in result && result.invoiceName ? result.invoiceName : null;
  const isReady = result?.status === "fulfilled" || result?.status === "already_processed";

  return (
    <div className="mx-auto max-w-lg text-center">
      <div className="rounded-2xl border bg-green-50 p-8">
        <div className="mx-auto flex h-16 w-16 items-center justify-center rounded-full bg-green-100 text-4xl">
          ✓
        </div>
        <h1 className="mt-4 text-2xl font-bold text-gray-900">Plata confirmata!</h1>
        <p className="mt-2 text-gray-600">
          {isReady
            ? "Serviciul a fost achizitionat cu succes. Factura a fost generata si marcata ca platita."
            : "Plata a fost confirmata de Stripe. Sincronizarea cu ERP este in curs."}
        </p>
        {session_id && (
          <p className="mt-2 text-xs text-gray-500">Referinta: {session_id}</p>
        )}
        {invoiceName && (
          <p className="mt-1 text-xs text-gray-500">Factura ERP: {invoiceName}</p>
        )}

        <div className="mt-6 flex flex-col gap-3 sm:flex-row sm:justify-center">
          <Link
            href="/dashboard/invoices"
            className="rounded-lg bg-teal-600 px-6 py-2.5 text-sm font-semibold text-white hover:bg-teal-700"
          >
            Vezi facturi
          </Link>
          <Link
            href="/dashboard"
            className="rounded-lg border px-6 py-2.5 text-sm font-medium text-gray-700 hover:bg-gray-50"
          >
            Inapoi la dashboard
          </Link>
        </div>
      </div>
    </div>
  );
}
