'use client'

import { useCallback, useEffect, useRef, useState } from 'react'
import Link from 'next/link'
import { CheckCircle2, Clock, Loader2, XCircle } from 'lucide-react'
import { Button } from '@/components/ui/button'
import { RETURN_COPY, returnStateFor, type ReturnState } from '@/lib/domain/purchases'
import type { PurchaseStatus } from '@/types/db'

const POLL_MS = 4_000
const POLL_MAX = 30 // ~2 minutes
const DELAYED_AFTER_MS = 3 * 60_000

function isPending(status: PurchaseStatus) {
  return returnStateFor(status, { delayed: false }) === 'pending'
}

/**
 * Shows one of the five return states with the exact task §13 copy. Polls
 * the purchase while pending and asks the server to reconcile once; it never
 * writes a payment status itself.
 */
export function ReturnStatus({ purchaseId, initialStatus, createdAt, totalCents, currency, tripHref }: {
  purchaseId: string
  initialStatus: PurchaseStatus
  createdAt: string
  totalCents: number
  currency: string
  tripHref: string
}) {
  const [status, setStatus] = useState<PurchaseStatus>(initialStatus)
  const [delayed, setDelayed] = useState(() => Date.now() - new Date(createdAt).getTime() > DELAYED_AFTER_MS)
  const [busy, setBusy] = useState(false)
  const [error, setError] = useState<string | null>(null)
  const polls = useRef(0)
  const reconciled = useRef(false)

  const refetch = useCallback(async (): Promise<PurchaseStatus | null> => {
    try {
      const res = await fetch(`/api/purchases/${purchaseId}`, { cache: 'no-store' })
      if (!res.ok) return null
      const json = (await res.json()) as { purchase?: { purchase_status: PurchaseStatus } }
      const next = json.purchase?.purchase_status ?? null
      if (next) setStatus(next)
      return next
    } catch {
      return null
    }
  }, [purchaseId])

  const reconcile = useCallback(async () => {
    try { await fetch(`/api/purchases/${purchaseId}/reconcile`, { method: 'POST' }) } catch { /* the next poll will tell */ }
  }, [purchaseId])

  useEffect(() => {
    if (!isPending(status)) return
    let cancelled = false
    const tick = async () => {
      if (cancelled) return
      polls.current += 1
      const next = await refetch()
      if (cancelled) return
      if (!reconciled.current) {
        reconciled.current = true
        await reconcile()
        if (!cancelled) await refetch()
      }
      if (cancelled || (next && !isPending(next))) return
      if (Date.now() - new Date(createdAt).getTime() > DELAYED_AFTER_MS) setDelayed(true)
      if (polls.current < POLL_MAX) timer = setTimeout(tick, POLL_MS)
      else setDelayed(true)
    }
    let timer = setTimeout(tick, POLL_MS)
    return () => { cancelled = true; clearTimeout(timer) }
  }, [status, createdAt, refetch, reconcile])

  const state: ReturnState = returnStateFor(status, { delayed })

  async function checkAgain() {
    setBusy(true)
    setError(null)
    await reconcile()
    await refetch()
    setBusy(false)
  }

  async function tryAgain() {
    setBusy(true)
    setError(null)
    try {
      const res = await fetch(`/api/purchases/${purchaseId}/checkout`, { method: 'POST' })
      const json = (await res.json()) as { checkout_url?: string; error?: string }
      if (res.ok && json.checkout_url) { window.location.assign(json.checkout_url); return }
      setError(json.error || 'Checkout could not be started. Please try again.')
    } catch {
      setError('Checkout could not be started. Please try again.')
    }
    setBusy(false)
  }

  const amount = new Intl.NumberFormat('en-US', { style: 'currency', currency: currency || 'USD' }).format(totalCents / 100)

  const icon = state === 'confirmed' ? <CheckCircle2 className="size-8 text-emerald-600" aria-hidden />
    : state === 'failed' || state === 'cancelled' ? <XCircle className="size-8 text-destructive" aria-hidden />
    : state === 'delayed' ? <Clock className="size-8 text-amber-600" aria-hidden />
    : <Loader2 className="size-8 animate-spin text-muted-foreground" aria-hidden />

  const title = state === 'confirmed' ? 'Payment confirmed'
    : state === 'failed' ? 'Payment not completed'
    : state === 'cancelled' ? 'Purchase cancelled'
    : state === 'delayed' ? 'Awaiting confirmation'
    : 'Checking payment'

  return (
    <div className="w-full max-w-md rounded-xl border border-border bg-card p-6 text-card-foreground shadow-sm">
      <div className="flex flex-col items-center gap-3 text-center">
        {icon}
        <h1 className="text-lg font-semibold">{title}</h1>
        <p className="text-sm text-muted-foreground" role="status" aria-live="polite">{RETURN_COPY[state]}</p>
        <p className="text-xs text-muted-foreground">Route purchase · {amount}</p>
        {error && <p className="text-sm text-destructive">{error}</p>}
      </div>
      <div className="mt-6 flex flex-col gap-2">
        {state === 'confirmed' && (
          <Button asChild><Link href={tripHref}>Back to trip</Link></Button>
        )}
        {state === 'failed' && (
          <>
            <Button onClick={tryAgain} disabled={busy}>{busy ? 'Starting checkout…' : 'Try again'}</Button>
            <Button asChild variant="outline"><Link href={tripHref}>Back to trip</Link></Button>
          </>
        )}
        {state === 'cancelled' && (
          <Button asChild variant="outline"><Link href={tripHref}>Back to trip</Link></Button>
        )}
        {state === 'delayed' && (
          <>
            <Button onClick={checkAgain} disabled={busy}>{busy ? 'Checking…' : 'Check again'}</Button>
            <Button asChild variant="outline"><Link href={tripHref}>Back to trip</Link></Button>
          </>
        )}
        {state === 'pending' && (
          <Button asChild variant="ghost"><Link href={tripHref}>Back to trip</Link></Button>
        )}
      </div>
    </div>
  )
}
