import { CheckCircle2, ExternalLink } from "lucide-react"
import Link from "next/link"

type PaymentData = {
  invoice_id?: string
  status?: string
}

async function getPayment(invoiceId: string) {
  // Try proxy first; ignore any errors and return empty object so UI stays clean.
  try {
    const res = await fetch(
      `${process.env.NEXT_PUBLIC_BASE_URL || ""}/api/payment-success?invoice_id=${encodeURIComponent(invoiceId)}`,
      { cache: "no-store", headers: { accept: "application/json" } },
    )
    if (res.ok) {
      return await res.json()
    }
  } catch {}
  // Fallback direct; still swallow errors.
  try {
    const res2 = await fetch(
      `https://pay.neonecy.com/api/payment-success?invoice_id=${encodeURIComponent(invoiceId)}`,
      { cache: "no-store", headers: { accept: "application/json" } },
    )
    if (res2.ok) {
      return await res2.json()
    }
  } catch {}
  return {} // never surface backend error messages
}

export default async function SuccessPage(props: any) {
  const sp = (await props?.searchParams) || props?.searchParams || {}
  const invoiceIdRaw = (sp?.invoice_id ?? sp?.invoiceId) as string | string[] | undefined
  const invoiceId = Array.isArray(invoiceIdRaw) ? invoiceIdRaw[0] : invoiceIdRaw

  if (!invoiceId) {
    return (
      <main className="mx-auto max-w-3xl px-4 py-16 text-center">
        <div className="mx-auto mb-6 w-12 text-green-600">
          <CheckCircle2 className="h-12 w-12" />
        </div>
        <h1 className="text-2xl font-semibold">Payment Successful</h1>
        <p className="mt-2 text-muted-foreground">
          Missing invoice_id. If you were redirected here from your backend, append {'"?invoice_id=..."'} to this URL.
        </p>
        <div className="mt-8">
          <Link href="/" className="text-primary underline inline-flex items-center gap-1">
            Go home <ExternalLink className="h-4 w-4" />
          </Link>
        </div>
      </main>
    )
  }

  const payload = await getPayment(invoiceId)
  const data: PaymentData = payload?.data ?? payload ?? {}

  const shownInvoiceId = data?.invoice_id || invoiceId
  const statusText = (data?.status || "COMPLETED").toString().toUpperCase()

  return (
    <main className="mx-auto max-w-3xl px-4 py-12">
      <div className="mb-6 flex items-center gap-3">
        <CheckCircle2 className="h-8 w-8 text-green-600" />
        <div>
          <h1 className="text-2xl font-semibold">Payment Successful</h1>
          {/* Intentionally do not render any backend message to avoid showing SQL or other errors */}
        </div>
      </div>

      <section className="rounded-lg border p-4 sm:p-6 bg-white">
        <dl className="grid grid-cols-1 sm:grid-cols-2 gap-x-6 gap-y-4">
          <div>
            <dt className="text-sm text-muted-foreground">Invoice ID</dt>
            <dd className="font-medium break-all">{shownInvoiceId}</dd>
          </div>
          <div>
            <dt className="text-sm text-muted-foreground">Status</dt>
            <dd className="font-medium">{statusText}</dd>
          </div>
        </dl>

        <div className="mt-8 flex flex-wrap items-center gap-3">
          <Link href="/" className="inline-flex items-center gap-2 rounded-md bg-black text-white px-4 py-2 text-sm">
            Continue <ExternalLink className="h-4 w-4" />
          </Link>
        </div>
      </section>
    </main>
  )
}
