import { useState } from 'react'
import { createFileRoute, Link, useRouter } from '@tanstack/react-router'
import { useServerFn } from '@tanstack/react-start'
import { Banknote, CircleAlert, Clock, Receipt, RefreshCw } from 'lucide-react'
import { toast } from 'sonner'
import { z } from 'zod'
import { Button } from '@/components/ui/button'
import { Skeleton } from '@/components/ui/skeleton'
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from '@/components/ui/table'
import {
  CustomerCell,
  EmptyState,
  Panel,
  PageIntro,
  StatusBadge,
  SummaryStrip,
  dateFormat,
  filterBarClass,
  filterClass,
  timeAgo,
} from '@/components/admin/AdminUi'
import { getAdminPayments, recheckPayment } from '@/lib/admin.functions'
import { formatCedis, getPackage } from '@/lib/pricing'

const statusSchema = z.enum(['all', 'pending', 'success', 'failed'])
type Status = z.infer<typeof statusSchema>

export const Route = createFileRoute('/admin/payments')({
  validateSearch: z.object({ status: statusSchema.catch('all') }),
  loaderDeps: ({ search }) => ({ status: search.status }),
  loader: ({ deps }) => getAdminPayments({ data: { status: deps.status } }),
  head: () => ({ meta: [{ title: 'Admin · Payments — AkotoCreative SMS' }] }),
  pendingComponent: () => <Skeleton className="h-96 rounded-2xl" />,
  component: PaymentsPage,
})

const FILTERS: { value: Status; label: string }[] = [
  { value: 'all', label: 'All' },
  { value: 'success', label: 'Paid' },
  { value: 'pending', label: 'Pending' },
  { value: 'failed', label: 'Failed' },
]

function PaymentsPage() {
  const { status } = Route.useSearch()
  const payments = Route.useLoaderData()
  const paid = payments.filter((p) => p.status === 'success')

  return (
    <div className="grid gap-6">
      <PageIntro eyebrow="Billing" title="Payments">
        Credit purchases made through Moolre, newest first. Credits are only added once Moolre confirms the payment.
        If a payment is stuck on pending, “Check with Moolre” asks for its latest status.
      </PageIntro>

      <SummaryStrip
        items={[
          { label: 'Shown', value: payments.length.toLocaleString(), icon: Receipt },
          { label: 'Paid total', value: formatCedis(paid.reduce((sum, p) => sum + p.amount, 0)), icon: Banknote },
          {
            label: 'Pending',
            value: payments.filter((p) => p.status === 'pending').length.toLocaleString(),
            icon: Clock,
            tone: 'gold',
          },
          {
            label: 'Failed',
            value: payments.filter((p) => p.status === 'failed').length.toLocaleString(),
            icon: CircleAlert,
            tone: 'red',
          },
        ]}
      />

      <nav aria-label="Payment status" className={filterBarClass}>
        {FILTERS.map((f) => (
          <Link
            key={f.value}
            to="/admin/payments"
            search={{ status: f.value }}
            className={filterClass(f.value === status)}
            aria-current={f.value === status ? 'page' : undefined}
          >
            {f.label}
          </Link>
        ))}
      </nav>

      {payments.length === 0 ? (
        <EmptyState icon={Receipt}>{status === 'all' ? 'No payments yet.' : 'No payments with this status.'}</EmptyState>
      ) : (
        <Panel>
          <Table>
            <TableHeader>
              <TableRow>
                <TableHead>Date</TableHead>
                <TableHead>Customer</TableHead>
                <TableHead>Bundle</TableHead>
                <TableHead className="text-right">Amount</TableHead>
                <TableHead>Status</TableHead>
                <TableHead>Reference</TableHead>
                <TableHead>
                  <span className="sr-only">Actions</span>
                </TableHead>
              </TableRow>
            </TableHeader>
            <TableBody>
              {payments.map((p) => (
                <TableRow key={p.reference}>
                  <TableCell className="whitespace-nowrap">
                    {dateFormat.format(new Date(p.createdAt))}
                    <p className="text-xs text-muted-foreground">{timeAgo(p.createdAt)}</p>
                  </TableCell>
                  <TableCell>
                    <CustomerCell email={p.email} detail={p.payerPhone} />
                  </TableCell>
                  <TableCell>
                    {getPackage(p.packageId)?.name ?? p.packageId}
                    <p className="text-xs text-muted-foreground tabular-nums">{p.credits.toLocaleString()} credits</p>
                  </TableCell>
                  <TableCell className="text-right font-semibold tabular-nums">{formatCedis(p.amount)}</TableCell>
                  <TableCell>
                    <StatusBadge status={p.status} />
                  </TableCell>
                  <TableCell className="font-mono text-xs text-muted-foreground">
                    {p.reference}
                    {p.providerReference && <p className="text-muted-foreground">Moolre: {p.providerReference}</p>}
                  </TableCell>
                  <TableCell className="text-right">
                    {p.status === 'pending' && <RecheckButton reference={p.reference} />}
                  </TableCell>
                </TableRow>
              ))}
            </TableBody>
          </Table>
        </Panel>
      )}
    </div>
  )
}

function RecheckButton({ reference }: { reference: string }) {
  const router = useRouter()
  const recheck = useServerFn(recheckPayment)
  const [checking, setChecking] = useState(false)

  async function run() {
    setChecking(true)
    try {
      const result = await recheck({ data: { reference } })
      if (result.status === 'success') toast.success('Payment confirmed. The credits have been added.')
      else if (result.status === 'failed') toast.error('Moolre reports this payment failed.')
      else toast.info('Moolre has not confirmed this payment yet.')
      await router.invalidate()
    } catch (err) {
      toast.error(err instanceof Error ? err.message : 'Could not reach Moolre.')
    } finally {
      setChecking(false)
    }
  }

  return (
    <Button size="sm" variant="outline" onClick={run} disabled={checking} className="whitespace-nowrap">
      <RefreshCw className={checking ? 'animate-spin motion-reduce:animate-none' : undefined} />
      {checking ? 'Checking…' : 'Check with Moolre'}
    </Button>
  )
}
