import { useEffect, useState } from 'react'
import { createFileRoute, Link, redirect } from '@tanstack/react-router'
import { useServerFn } from '@tanstack/react-start'
import { CheckCircle2, Clock, XCircle } from 'lucide-react'
import { z } from 'zod'
import { Button } from '@/components/ui/button'
import { getServerUser } from '@/lib/identity.functions'
import { confirmPayment } from '@/lib/account.functions'
import { formatCedis } from '@/lib/pricing'

export const Route = createFileRoute('/payment')({
  validateSearch: z.object({ ref: z.string().optional() }),
  beforeLoad: async () => {
    const user = await getServerUser()
    if (!user) throw redirect({ to: '/login' })
  },
  head: () => ({ meta: [{ title: 'Payment status — AkotoCreative SMS' }] }),
  component: PaymentPage,
})

type Result = Awaited<ReturnType<typeof confirmPayment>>

const POLL_MS = 4000
const MAX_ATTEMPTS = 30

function PaymentPage() {
  const { ref } = Route.useSearch()
  const confirm = useServerFn(confirmPayment)
  const [result, setResult] = useState<Result | undefined>(undefined)
  const [attempts, setAttempts] = useState(0)
  const [error, setError] = useState(false)

  useEffect(() => {
    if (!ref) return
    let cancelled = false
    let timer: ReturnType<typeof setTimeout>
    let count = 0
    async function check() {
      try {
        const next = await confirm({ data: { reference: ref! } })
        if (cancelled) return
        setResult(next)
        setError(false)
        count += 1
        setAttempts(count)
        if (next?.status === 'pending' && count < MAX_ATTEMPTS) timer = setTimeout(check, POLL_MS)
      } catch {
        if (!cancelled) {
          setError(true)
          count += 1
          if (count < MAX_ATTEMPTS) timer = setTimeout(check, POLL_MS)
        }
      }
    }
    void check()
    return () => {
      cancelled = true
      clearTimeout(timer)
    }
  }, [ref, confirm])

  let body: React.ReactNode
  if (!ref || result === null) {
    body = (
      <State icon={<XCircle className="size-12 text-destructive" />} title="Payment not found">
        We couldn’t find that payment on your account.
      </State>
    )
  } else if (result === undefined) {
    body = (
      <State icon={<Clock className="size-12 animate-pulse text-primary motion-reduce:animate-none" />} title="Checking your payment…">
        {error ? 'Still trying to reach the payment service…' : 'This usually takes a few seconds.'}
      </State>
    )
  } else if (result.status === 'success') {
    body = (
      <State icon={<CheckCircle2 className="size-12 text-primary" />} title="Payment received">
        {result.credits.toLocaleString()} credits were added for {formatCedis(result.amount)}. Your balance is now{' '}
        <strong className="text-foreground">{result.balance.toLocaleString()}</strong> credits.
      </State>
    )
  } else if (result.status === 'failed') {
    body = (
      <State icon={<XCircle className="size-12 text-destructive" />} title="Payment didn’t go through">
        No money was taken and no credits were added. You can try again with another wallet or card.
      </State>
    )
  } else {
    body = (
      <State icon={<Clock className="size-12 animate-pulse text-accent-foreground motion-reduce:animate-none" />} title="Waiting for confirmation">
        {attempts >= MAX_ATTEMPTS
          ? 'We haven’t heard back yet. If you approved the payment, your credits will appear on your dashboard shortly.'
          : 'Approve the prompt on your phone if you haven’t yet. We’ll update this page automatically.'}
      </State>
    )
  }

  return (
    <div className="mx-auto max-w-reading px-4 py-20 sm:px-6">
      <div className="rounded-2xl border bg-card p-10 text-center">
        {body}
        <div className="mt-8 flex flex-wrap justify-center gap-3">
          <Button asChild>
            <Link to="/dashboard">Go to dashboard</Link>
          </Button>
          {result?.status === 'failed' && (
            <Button asChild variant="outline">
              <Link to="/buy">Try again</Link>
            </Button>
          )}
        </div>
      </div>
    </div>
  )
}

function State({ icon, title, children }: { icon: React.ReactNode; title: string; children: React.ReactNode }) {
  return (
    <div role="status" className="grid justify-items-center gap-3">
      {icon}
      <h1 className="text-3xl font-extrabold">{title}</h1>
      <p className="max-w-md text-muted-foreground">{children}</p>
    </div>
  )
}
