'use client'

import { Suspense, useEffect, useState } from 'react'
import Link from 'next/link'
import { useSearchParams } from 'next/navigation'
import { api } from '@/lib/api'
import { sanitizeHtml } from '@/lib/format'

type State = 'checking' | 'success' | 'failed' | 'pending'

function ReturnInner() {
  const params = useSearchParams()
  const [state, setState] = useState<State>('checking')
  const [ref, setRef] = useState<string | null>(null)

  // Safepay/gateway may append various params; support the common ones.
  const paymentId = params.get('payment') || params.get('payment_id')
  const orderRef = params.get('order_id') || params.get('reference') || params.get('tracker')
  const statusParam = (params.get('status') || '').toLowerCase()

  useEffect(() => {
    setRef(orderRef)
    if (statusParam === 'cancelled' || statusParam === 'failed' || statusParam === 'declined') {
      setState('failed'); return
    }
    if (!paymentId) {
      // No payment id to confirm against — treat gateway-reported success as success, else pending.
      setState(statusParam === 'paid' || statusParam === 'success' || statusParam === 'completed' ? 'success' : 'pending')
      return
    }
    api.post<{ status?: string; gateway_reference?: string }>(`/payments/${paymentId}/confirm`, {}, true)
      .then((r) => {
        const s = (r.status || '').toLowerCase()
        setRef(r.gateway_reference || orderRef)
        setState(s === 'paid' || s === 'completed' || s === 'success' ? 'success' : s === 'failed' || s === 'cancelled' ? 'failed' : 'pending')
      })
      .catch(() => setState('pending'))
  }, [paymentId, orderRef, statusParam])

  const config = {
    checking: { icon: '⏳', color: 'text-muted', title: 'Confirming your payment…', body: 'Please wait while we verify the transaction.' },
    success: { icon: '✓', color: 'text-brand-strong', title: 'Payment successful', body: 'Your payment has been confirmed. Thank you!' },
    failed: { icon: '✕', color: 'text-rose-600', title: 'Payment not completed', body: 'The payment was cancelled or failed. You can try again from your cart.' },
    pending: { icon: '…', color: 'text-amber-600', title: 'Payment is processing', body: 'We&rsquo;ve received your request and will confirm shortly. Check your orders for the latest status.' },
  }[state]

  return (
    <div className="container-x py-16">
      <div className="mx-auto max-w-md card p-8 text-center">
        <div className={`mx-auto grid h-14 w-14 place-items-center rounded-full bg-soft text-2xl ${config.color}`}>{config.icon}</div>
        <h1 className="mt-4 text-xl font-bold">{config.title}</h1>
        <p className="mt-2 text-sm text-muted" dangerouslySetInnerHTML={{ __html: sanitizeHtml(config.body) }} />
        {ref && <p className="mt-2 text-[13px] text-muted">Reference: <span className="font-semibold text-ink">{ref}</span></p>}
        <div className="mt-6 flex flex-col gap-2">
          {state === 'success' && (
            <>
              <Link href="/account/orders" className="btn btn-primary">View my orders</Link>
              <Link href="/account?tab=bookings" className="btn btn-ghost">My bookings</Link>
            </>
          )}
          {state === 'failed' && <Link href="/cart" className="btn btn-primary">Back to cart</Link>}
          {state === 'pending' && <Link href="/account/orders" className="btn btn-primary">Check status</Link>}
          {state === 'checking' && <Link href="/account/orders" className="btn btn-ghost">View my orders</Link>}
          <Link href="/" className="text-sm text-muted hover:underline">Continue shopping</Link>
        </div>
      </div>
    </div>
  )
}

export default function PaymentReturnPage() {
  return <Suspense fallback={<div className="container-x py-16 text-center text-muted">Loading…</div>}><ReturnInner /></Suspense>
}
