import { useCallback, useEffect, useState, type ComponentType, type ReactNode } from 'react'
import { createFileRoute, Link } from '@tanstack/react-router'
import {
  Activity,
  ArrowRight,
  BadgeCheck,
  Banknote,
  Clock,
  Coins,
  Crown,
  MessageSquareText,
  Package,
  PhoneCall,
  Receipt,
  RefreshCw,
  Send,
  Sparkles,
  TriangleAlert,
  Users,
  Wallet,
} from 'lucide-react'
import { Button } from '@/components/ui/button'
import { Skeleton } from '@/components/ui/skeleton'
import { Avatar, Delta, EmptyState, StatusBadge, percentChange, timeAgo } from '@/components/admin/AdminUi'
import { Donut, Sparkline, TrendChart, type DonutSegment } from '@/components/admin/charts'
import { getAdminOverview, getMainBalance } from '@/lib/admin.functions'
import { PACKAGES, formatCedis } from '@/lib/pricing'
import { cn } from '@/lib/utils'
import { voiceLabel } from '@/lib/voice'

export const Route = createFileRoute('/admin/')({
  loader: () => getAdminOverview(),
  head: () => ({ meta: [{ title: 'Admin overview — AkotoCreative SMS' }] }),
  pendingComponent: OverviewSkeleton,
  component: Overview,
})

type OverviewData = Awaited<ReturnType<typeof getAdminOverview>>

const compact = new Intl.NumberFormat('en-GH', { notation: 'compact', maximumFractionDigits: 1 })
const cedisAxis = (n: number) => `GH₵${compact.format(n)}`

function greeting() {
  // Ghana is on UTC all year.
  const hour = new Date().getUTCHours()
  return hour < 12 ? 'Good morning' : hour < 17 ? 'Good afternoon' : 'Good evening'
}

function Overview() {
  const data = Route.useLoaderData()

  return (
    <div className="grid gap-8">
      <Hero data={data} />
      <MainBalance outstandingCredits={data.customers.outstandingCredits} />
      <KpiRow data={data} />

      <div className="grid gap-6 lg:grid-cols-3">
        <Card
          className="lg:col-span-2"
          icon={Send}
          title="Message volume"
          sub="SMS credits used per day, after refunds for failed batches (voice is shown below)"
          action={<ViewAll to="/admin/messages" />}
        >
          <TrendChart data={data.trends.sends} variant="bar" label="SMS credits used" format={(n) => compact.format(n)} />
        </Card>
        <DeliveryHealth data={data} />
      </div>

      <VoiceSms data={data} />

      <div className="grid gap-6 lg:grid-cols-2">
        <BundleMix data={data} />
        <TopCustomers data={data} />
      </div>

      <div className="grid gap-6 lg:grid-cols-2">
        <Card icon={Receipt} title="Latest payments" action={<ViewAll to="/admin/payments" />}>
          {data.recentPayments.length === 0 ? (
            <EmptyState icon={Receipt}>No payments yet.</EmptyState>
          ) : (
            <ul className="-mx-2 grid">
              {data.recentPayments.map((p) => (
                <FeedItem
                  key={p.reference}
                  email={p.email}
                  meta={`${p.credits.toLocaleString()} credits · ${timeAgo(p.createdAt)}`}
                  value={formatCedis(p.amount)}
                  status={p.status}
                />
              ))}
            </ul>
          )}
        </Card>
        <Card icon={MessageSquareText} title="Latest sends" action={<ViewAll to="/admin/messages" />}>
          {data.recentCampaigns.length === 0 ? (
            <EmptyState icon={MessageSquareText}>No messages sent yet.</EmptyState>
          ) : (
            <ul className="-mx-2 grid">
              {data.recentCampaigns.map((c) => (
                <FeedItem
                  key={c.id}
                  email={c.email}
                  meta={`${c.channel === 'voice' ? 'Voice' : c.senderId} · ${timeAgo(c.createdAt)}`}
                  value={`${c.recipientCount.toLocaleString()} ${c.recipientCount === 1 ? 'number' : 'numbers'}`}
                  status={c.status}
                />
              ))}
            </ul>
          )}
        </Card>
      </div>
    </div>
  )
}

function Hero({ data }: { data: OverviewData }) {
  const avgOrder = data.revenue.recentCount > 0 ? data.revenue.recent / data.revenue.recentCount : 0
  const change = percentChange(data.revenue.recent, data.revenue.previous)

  return (
    <section aria-labelledby="hero-heading" className="stage grain relative overflow-hidden rounded-[2rem] shadow-deep">
      <div className="aurora" aria-hidden />
      <div className="line-grid pointer-events-none absolute inset-0 [mask-image:radial-gradient(ellipse_at_top_right,black,transparent_70%)]" aria-hidden />
      <div className="relative z-10 grid gap-8 p-6 sm:p-8 xl:grid-cols-[1fr_17rem]">
        <div className="grid min-w-0 gap-6">
          <div className="flex flex-wrap items-start justify-between gap-4">
            <div className="grid gap-1">
              <p className="flex items-center gap-2 text-sm text-white/60" suppressHydrationWarning>
                <Sparkles className="size-4 text-[var(--gold-glow)]" aria-hidden /> {greeting()}
              </p>
              <h1 id="hero-heading" className="text-3xl font-extrabold text-white sm:text-4xl">
                Overview
              </h1>
            </div>
            <div className="grid justify-items-end gap-1 text-right">
              <p className="text-xs font-medium tracking-[0.14em] text-white/55 uppercase">Revenue · last 30 days</p>
              <p className="text-gold font-display text-4xl font-extrabold tabular-nums sm:text-5xl">
                {formatCedis(data.revenue.recent)}
              </p>
              <p className="flex items-center gap-2 text-xs text-white/60">
                <span
                  className={cn(
                    'rounded-full px-2 py-0.5 font-semibold tabular-nums ring-1 ring-inset',
                    change === null || change >= 0
                      ? 'bg-emerald-400/15 text-emerald-300 ring-emerald-300/25'
                      : 'bg-red-400/15 text-red-300 ring-red-300/25',
                  )}
                >
                  {change === null ? 'New' : `${change >= 0 ? '▲' : '▼'} ${Math.abs(change).toFixed(0)}%`}
                </span>
                vs. {formatCedis(data.revenue.previous)} the 30 days before
              </p>
            </div>
          </div>
          <TrendChart data={data.trends.revenue} tone="dark" label="Daily revenue" format={cedisAxis} />
        </div>

        <div className="grid content-start gap-3 sm:grid-cols-2 xl:grid-cols-1">
          <GlassStat icon={Banknote} label="All-time revenue" value={formatCedis(data.revenue.total)} />
          <GlassStat
            icon={Receipt}
            label="Payments, 30 days"
            value={data.revenue.recentCount.toLocaleString()}
            note={avgOrder > 0 ? `${formatCedis(avgOrder)} average` : undefined}
          />
          <Attention
            count={data.pending.senderIds}
            icon={BadgeCheck}
            label={`sender ID ${plural(data.pending.senderIds, 'request')} to review`}
            to="/admin/sender-ids"
            status="pending"
          />
          <Attention
            count={data.pending.payments}
            icon={Clock}
            label={`${plural(data.pending.payments, 'payment')} not yet confirmed`}
            to="/admin/payments"
            status="pending"
          />
        </div>
      </div>
    </section>
  )
}

function GlassStat({
  icon: Icon,
  label,
  value,
  note,
}: {
  icon: ComponentType<{ className?: string }>
  label: string
  value: string
  note?: string
}) {
  return (
    <div className="glass flex items-center gap-3 rounded-2xl p-4">
      <span className="grid size-10 shrink-0 place-items-center rounded-xl bg-white/10 text-[var(--gold-glow)]">
        <Icon className="size-5" aria-hidden />
      </span>
      <div className="min-w-0">
        <p className="text-xs text-white/55">{label}</p>
        <p className="truncate font-display text-xl font-bold text-white tabular-nums">{value}</p>
        {note && <p className="text-xs text-[var(--gold-glow)]">{note}</p>}
      </div>
    </div>
  )
}

function Attention({
  count,
  icon: Icon,
  label,
  to,
  status,
}: {
  count: number
  icon: ComponentType<{ className?: string }>
  label: string
  to: '/admin/sender-ids' | '/admin/payments'
  status: 'pending'
}) {
  if (count === 0) {
    return (
      <p className="flex items-center gap-3 rounded-2xl border border-white/10 px-4 py-3 text-sm text-white/50">
        <Icon className="size-4" aria-hidden /> No {label} · all clear
      </p>
    )
  }
  return (
    <Link
      to={to}
      search={{ status }}
      className="group flex items-center gap-3 rounded-2xl border border-[var(--gold-glow)]/40 bg-[var(--gold-glow)]/12 px-4 py-3 text-sm font-medium text-white transition-colors hover:bg-[var(--gold-glow)]/20"
    >
      <span className="pulse-dot size-2 shrink-0 rounded-full bg-[var(--gold-glow)]" aria-hidden />
      <span className="flex-1">
        <strong className="font-display tabular-nums">{count.toLocaleString()}</strong> {label}
      </span>
      <ArrowRight className="size-4 text-[var(--gold-glow)] transition-transform group-hover:translate-x-0.5" aria-hidden />
    </Link>
  )
}

function KpiRow({ data }: { data: OverviewData }) {
  const sold = data.revenue.creditsSold
  const unusedShare = sold > 0 ? Math.min(data.customers.outstandingCredits / sold, 1) : 0
  return (
    <dl className="grid gap-4 sm:grid-cols-2 xl:grid-cols-4">
      <Kpi
        icon={MessageSquareText}
        label="SMS credits used"
        value={data.sends.recent.toLocaleString()}
        delta={<Delta current={data.sends.recent} previous={data.sends.previous} />}
        detail={`${data.sends.total.toLocaleString()} all time`}
        spark={data.trends.sends.map((d) => d.value)}
      />
      <Kpi
        icon={Users}
        label="New customers"
        value={data.customers.recent.toLocaleString()}
        delta={<Delta current={data.customers.recent} previous={data.customers.previous} />}
        detail={`${data.customers.total.toLocaleString()} total · ${data.customers.withBalance.toLocaleString()} with credit`}
        spark={data.trends.signups.map((d) => d.value)}
      />
      <Kpi
        icon={Send}
        label="Numbers reached"
        value={data.sends.recipients.toLocaleString()}
        detail={
          data.sends.failed > 0
            ? `${data.sends.failed.toLocaleString()} failed ${plural(data.sends.failed, 'send')} this month`
            : 'No failed sends this month'
        }
        tone={data.sends.failed > 0 ? 'warn' : undefined}
      />
      <Kpi
        icon={Coins}
        label="Unused credit"
        value={data.customers.outstandingCredits.toLocaleString()}
        detail={`of ${sold.toLocaleString()} credits sold`}
      >
        <div className="mt-3 h-1.5 overflow-hidden rounded-full bg-muted" aria-hidden>
          <div
            className="h-full rounded-full bg-gradient-to-r from-primary to-[var(--gold-glow)]"
            style={{ width: `${unusedShare * 100}%` }}
          />
        </div>
      </Kpi>
    </dl>
  )
}

function Kpi({
  icon: Icon,
  label,
  value,
  delta,
  detail,
  spark,
  tone,
  children,
}: {
  icon: ComponentType<{ className?: string }>
  label: string
  value: string
  delta?: ReactNode
  detail: string
  spark?: number[]
  tone?: 'warn'
  children?: ReactNode
}) {
  return (
    <div className="gradient-border group relative flex flex-col overflow-hidden rounded-2xl bg-card p-5 shadow-deep transition-transform hover:-translate-y-0.5 [--ring-from:color-mix(in_oklch,var(--gold-glow)_60%,transparent)] [--ring-to:color-mix(in_oklch,var(--primary)_35%,transparent)]">
      <div
        className="pointer-events-none absolute -top-12 -right-12 size-32 rounded-full bg-[radial-gradient(circle,color-mix(in_oklch,var(--gold-glow)_35%,transparent),transparent_70%)] opacity-0 transition-opacity group-hover:opacity-100"
        aria-hidden
      />
      <dt className="flex items-center justify-between gap-2">
        <span className="flex items-center gap-2 text-xs font-semibold tracking-wide text-muted-foreground uppercase">
          <span className="grid size-8 place-items-center rounded-lg bg-primary/10 text-primary ring-1 ring-primary/15 ring-inset">
            <Icon className="size-4" aria-hidden />
          </span>
          {label}
        </span>
        {delta}
      </dt>
      <dd className="mt-3 font-display text-3xl font-extrabold tabular-nums">{value}</dd>
      <dd className={cn('text-sm', tone === 'warn' ? 'text-destructive' : 'text-muted-foreground')}>{detail}</dd>
      {spark && (
        <dd className="mt-auto pt-3 text-primary">
          <Sparkline values={spark} />
        </dd>
      )}
      {children && <dd>{children}</dd>}
    </div>
  )
}

type MainBalanceData = Awaited<ReturnType<typeof getMainBalance>>

// Provider balances are fetched after the page renders, so a slow Moolre or
// Africa's Talking response never holds up the overview.
function MainBalance({ outstandingCredits }: { outstandingCredits: number }) {
  const [balance, setBalance] = useState<MainBalanceData | null>(null)
  const [loading, setLoading] = useState(true)
  const [failed, setFailed] = useState(false)

  const fetchBalance = useCallback(() => {
    getMainBalance()
      .then((result) => {
        setBalance(result)
        setFailed(false)
      })
      .catch(() => setFailed(true))
      .finally(() => setLoading(false))
  }, [])

  useEffect(fetchBalance, [fetchBalance])

  function load() {
    setLoading(true)
    fetchBalance()
  }

  const sms = balance?.sms
  const shortfall = sms?.state === 'ok' ? outstandingCredits - sms.balance : 0

  return (
    <Card
      icon={Wallet}
      title="Main balance"
      sub={
        balance
          ? `What is left on the provider accounts every send draws on · checked ${timeAgo(balance.checkedAt)}`
          : 'What is left on the provider accounts every send draws on'
      }
      action={
        <Button variant="outline" size="sm" className="rounded-full" onClick={load} disabled={loading}>
          <RefreshCw className={cn('size-3.5', loading && 'animate-spin')} aria-hidden /> Refresh
        </Button>
      }
    >
      {failed && !balance ? (
        <p className="text-sm text-destructive">We could not load the balances. Try refreshing.</p>
      ) : (
        <div className="grid gap-4 md:grid-cols-3" aria-busy={loading}>
          <BalanceTile
            icon={MessageSquareText}
            label="Moolre SMS balance"
            result={balance?.sms}
            format={(n) => `${Number(n).toLocaleString()} SMS`}
            loading={loading && !balance}
          />
          <BalanceTile
            icon={PhoneCall}
            label="Africa's Talking voice balance"
            result={balance?.voice}
            format={String}
            loading={loading && !balance}
          />
          <div className="grid content-start gap-1 rounded-2xl bg-muted/60 p-4">
            <p className="flex items-center gap-2 text-xs font-semibold tracking-wide text-muted-foreground uppercase">
              <Coins className="size-4" aria-hidden /> Owed to customers
            </p>
            <p className="font-display text-2xl font-extrabold tabular-nums">{outstandingCredits.toLocaleString()} credits</p>
            {shortfall > 0 ? (
              <p className="flex items-start gap-1.5 text-sm text-destructive">
                <TriangleAlert className="mt-0.5 size-4 shrink-0" aria-hidden />
                {shortfall.toLocaleString()} more than the Moolre SMS balance. Top up on Moolre.
              </p>
            ) : (
              <p className="text-sm text-muted-foreground">Unused customer credit, all channels</p>
            )}
          </div>
        </div>
      )}
    </Card>
  )
}

function BalanceTile({
  icon: Icon,
  label,
  result,
  format,
  loading,
}: {
  icon: ComponentType<{ className?: string }>
  label: string
  result: MainBalanceData['sms'] | MainBalanceData['voice'] | undefined
  format: (value: number | string) => string
  loading: boolean
}) {
  return (
    <div className="gradient-border grid content-start gap-1 rounded-2xl bg-card p-4 [--ring-from:color-mix(in_oklch,var(--gold-glow)_60%,transparent)] [--ring-to:color-mix(in_oklch,var(--primary)_35%,transparent)]">
      <p className="flex items-center gap-2 text-xs font-semibold tracking-wide text-muted-foreground uppercase">
        <Icon className="size-4 text-primary" aria-hidden /> {label}
      </p>
      {loading || !result ? (
        <Skeleton className="h-8 w-32" />
      ) : result.state === 'ok' ? (
        <p className="font-display text-2xl font-extrabold tabular-nums">{format(result.balance)}</p>
      ) : (
        <>
          <p className="font-display text-2xl font-extrabold text-muted-foreground">—</p>
          <p className={cn('text-sm', result.state === 'error' ? 'text-destructive' : 'text-muted-foreground')}>
            {result.message}{' '}
            <Link to="/admin/settings" className="font-medium text-primary underline-offset-2 hover:underline">
              Settings
            </Link>
          </p>
        </>
      )}
    </div>
  )
}

const CALL_OUTCOMES: { label: string; statuses: string[]; color: string }[] = [
  { label: 'Answered', statuses: ['answered', 'completed'], color: 'var(--primary)' },
  { label: 'Ringing / queued', statuses: ['queued'], color: 'var(--gold-glow)' },
  { label: 'Missed (refunded)', statuses: ['failed'], color: 'var(--destructive)' },
]

function VoiceSms({ data }: { data: OverviewData }) {
  const { voice } = data
  const byStatus = new Map(voice.calls.map((c) => [c.status, c.count]))
  const outcomes = CALL_OUTCOMES.map((o) => ({ ...o, value: o.statuses.reduce((sum, st) => sum + (byStatus.get(st) ?? 0), 0) }))
  const totalCalls = outcomes.reduce((sum, o) => sum + o.value, 0)
  const answerRate = totalCalls > 0 ? Math.round((outcomes[0].value / totalCalls) * 100) : null

  return (
    <Card
      icon={PhoneCall}
      title="Voice SMS"
      sub="Text read aloud by phone call through Africa's Talking, last 30 days"
      action={
        <Link to="/admin/messages" search={{ status: 'all', channel: 'voice' }} className={viewAllClass}>
          View all <ArrowRight className="size-3 transition-transform group-hover:translate-x-0.5" aria-hidden />
        </Link>
      }
    >
      <dl className="grid grid-cols-2 gap-3 lg:grid-cols-4">
        <VoiceStat label="Voice sends" value={voice.sends.toLocaleString()} note={`${voice.customers.toLocaleString()} ${plural(voice.customers, 'customer')}`} />
        <VoiceStat label="Numbers called" value={voice.numbers.toLocaleString()} />
        <VoiceStat
          label="Credits used"
          value={voice.recent.toLocaleString()}
          note={`${voice.total.toLocaleString()} all time`}
          delta={<Delta current={voice.recent} previous={voice.previous} />}
        />
        <VoiceStat label="Answer rate" value={answerRate === null ? '—' : `${answerRate}%`} note={`${totalCalls.toLocaleString()} ${plural(totalCalls, 'call')}`} />
      </dl>

      <div className="grid gap-6 lg:grid-cols-[2fr_1fr]">
        <TrendChart data={data.trends.voice} variant="bar" label="Voice credits used" format={(n) => compact.format(n)} />
        <div className="grid content-start gap-4">
          <p className="text-sm font-semibold">Call outcomes</p>
          {outcomes.map((o) => (
            <div key={o.label} className="grid gap-1.5">
              <div className="flex items-baseline justify-between gap-3 text-sm">
                <span className="flex items-center gap-2 text-muted-foreground">
                  <span className="size-2.5 rounded-full" style={{ background: o.color }} aria-hidden />
                  {o.label}
                </span>
                <span className="font-semibold tabular-nums">{o.value.toLocaleString()}</span>
              </div>
              <div className="h-2 overflow-hidden rounded-full bg-muted" aria-hidden>
                <div
                  className="h-full rounded-full"
                  style={{ width: `${totalCalls > 0 ? (o.value / totalCalls) * 100 : 0}%`, background: o.color }}
                />
              </div>
            </div>
          ))}
        </div>
      </div>

      <div className="grid gap-2">
        <p className="text-sm font-semibold">Latest voice sends</p>
        {voice.latest.length === 0 ? (
          <EmptyState icon={PhoneCall}>No voice SMS sent yet.</EmptyState>
        ) : (
          <ul className="-mx-2 grid">
            {voice.latest.map((c) => (
              <FeedItem
                key={c.id}
                email={c.email}
                meta={`${voiceLabel(c.voice)} voice · ${c.answered.toLocaleString()} answered · ${c.missed.toLocaleString()} missed · ${timeAgo(c.createdAt)}`}
                value={`${c.recipientCount.toLocaleString()} ${c.recipientCount === 1 ? 'number' : 'numbers'}`}
                status={c.status}
              />
            ))}
          </ul>
        )}
      </div>
    </Card>
  )
}

function VoiceStat({ label, value, note, delta }: { label: string; value: string; note?: string; delta?: ReactNode }) {
  return (
    <div className="grid content-start gap-1 rounded-2xl bg-muted/60 p-4">
      <dt className="flex items-center justify-between gap-2 text-xs font-semibold tracking-wide text-muted-foreground uppercase">
        {label}
        {delta}
      </dt>
      <dd className="font-display text-2xl font-extrabold tabular-nums">{value}</dd>
      {note && <dd className="text-xs text-muted-foreground">{note}</dd>}
    </div>
  )
}

const DELIVERY: { status: string; label: string; color: string }[] = [
  { status: 'sent', label: 'Sent', color: 'var(--primary)' },
  { status: 'partial', label: 'Partly sent', color: 'var(--gold-glow)' },
  { status: 'failed', label: 'Failed', color: 'var(--destructive)' },
  { status: 'sending', label: 'Sending', color: 'oklch(0.7 0.06 200)' },
  { status: 'scheduled', label: 'Scheduled', color: 'oklch(0.75 0.05 260)' },
]

function DeliveryHealth({ data }: { data: OverviewData }) {
  const counts = new Map(data.campaignStatuses.map((s) => [s.status, s.count]))
  const segments: DonutSegment[] = DELIVERY.map((d) => ({ label: d.label, value: counts.get(d.status) ?? 0, color: d.color }))
  const total = segments.reduce((s, x) => s + x.value, 0)
  const sent = counts.get('sent') ?? 0

  return (
    <Card icon={Activity} title="Delivery health" sub="Sends in the last 30 days">
      {total === 0 ? (
        <EmptyState icon={Activity}>No sends in the last 30 days.</EmptyState>
      ) : (
        <div className="grid gap-5">
          <Donut segments={segments} center={`${Math.round((sent / total) * 100)}%`} sub="fully sent" />
          <ul className="grid grid-cols-2 gap-2 text-sm">
            {segments.map((s) => (
              <li key={s.label} className="flex items-center gap-2 rounded-lg bg-muted/60 px-2.5 py-1.5">
                <span className="size-2.5 rounded-full" style={{ background: s.color }} aria-hidden />
                <span className="flex-1 text-muted-foreground">{s.label}</span>
                <span className="font-semibold tabular-nums">{s.value.toLocaleString()}</span>
              </li>
            ))}
          </ul>
        </div>
      )}
    </Card>
  )
}

function BundleMix({ data }: { data: OverviewData }) {
  const byId = new Map(data.bundleMix.map((b) => [b.packageId, b]))
  const rows = [
    ...PACKAGES.map((p) => ({ id: p.id, name: p.name, count: byId.get(p.id)?.count ?? 0, amount: byId.get(p.id)?.amount ?? 0 })),
    // Bundles that are no longer on sale still show up if they were bought.
    ...data.bundleMix
      .filter((b) => !PACKAGES.some((p) => p.id === b.packageId))
      .map((b) => ({ id: b.packageId, name: b.packageId, count: b.count, amount: b.amount })),
  ]
  const max = Math.max(...rows.map((r) => r.amount), 1)
  const total = rows.reduce((s, r) => s + r.amount, 0)

  return (
    <Card icon={Package} title="Bundle mix" sub="Revenue by credit bundle, last 30 days">
      <ul className="grid gap-4">
        {rows.map((r, i) => (
          <li key={r.id} className="grid gap-1.5">
            <div className="flex items-baseline justify-between gap-3 text-sm">
              <span className="font-medium">
                {r.name}{' '}
                <span className="text-xs text-muted-foreground">
                  · {r.count.toLocaleString()} {plural(r.count, 'sale')}
                </span>
              </span>
              <span className="font-semibold tabular-nums">
                {formatCedis(r.amount)}
                {total > 0 && (
                  <span className="ml-2 text-xs font-normal text-muted-foreground">{Math.round((r.amount / total) * 100)}%</span>
                )}
              </span>
            </div>
            <div className="h-2.5 overflow-hidden rounded-full bg-muted" aria-hidden>
              <div
                className={cn(
                  'h-full rounded-full transition-[width] duration-700',
                  i % 2 === 0 ? 'bg-gradient-to-r from-primary to-[oklch(0.55_0.12_160)]' : 'bg-gradient-to-r from-[oklch(0.72_0.16_62)] to-[var(--gold-glow)]',
                )}
                style={{ width: `${(r.amount / max) * 100}%` }}
              />
            </div>
          </li>
        ))}
      </ul>
    </Card>
  )
}

function TopCustomers({ data }: { data: OverviewData }) {
  const max = Math.max(...data.topCustomers.map((c) => c.spent), 1)
  return (
    <Card icon={Crown} title="Top customers" sub="By total paid, all time" action={<ViewAll to="/admin/customers" />}>
      {data.topCustomers.length === 0 ? (
        <EmptyState icon={Crown}>No paying customers yet.</EmptyState>
      ) : (
        <ol className="grid gap-3">
          {data.topCustomers.map((c, i) => (
            <li key={c.userId} className="flex items-center gap-3">
              <span
                className={cn(
                  'grid size-6 shrink-0 place-items-center rounded-full font-display text-xs font-bold',
                  i === 0 ? 'btn-gold' : 'bg-muted text-muted-foreground',
                )}
              >
                {i + 1}
              </span>
              <Avatar email={c.email} />
              <div className="min-w-0 flex-1">
                <div className="flex items-baseline justify-between gap-3">
                  <p className="truncate text-sm font-medium">{c.email}</p>
                  <p className="shrink-0 text-sm font-semibold tabular-nums">{formatCedis(c.spent)}</p>
                </div>
                <div className="mt-1 flex items-center gap-2">
                  <div className="h-1.5 flex-1 overflow-hidden rounded-full bg-muted" aria-hidden>
                    <div
                      className="h-full rounded-full bg-gradient-to-r from-primary to-[var(--gold-glow)]"
                      style={{ width: `${(c.spent / max) * 100}%` }}
                    />
                  </div>
                  <span className="text-xs text-muted-foreground tabular-nums">{c.credits.toLocaleString()} left</span>
                </div>
              </div>
            </li>
          ))}
        </ol>
      )}
    </Card>
  )
}

function FeedItem({ email, meta, value, status }: { email: string; meta: string; value: string; status: string }) {
  return (
    <li className="flex items-center gap-3 rounded-xl px-2 py-2.5 transition-colors hover:bg-secondary/50">
      <Avatar email={email} />
      <div className="min-w-0 flex-1">
        <p className="truncate text-sm font-medium">{email || 'Unknown'}</p>
        <p className="truncate text-xs text-muted-foreground">{meta}</p>
      </div>
      <div className="grid justify-items-end gap-1">
        <span className="text-sm font-semibold tabular-nums">{value}</span>
        <StatusBadge status={status} />
      </div>
    </li>
  )
}

function Card({
  icon: Icon,
  title,
  sub,
  action,
  className,
  children,
}: {
  icon: ComponentType<{ className?: string }>
  title: string
  sub?: string
  action?: ReactNode
  className?: string
  children: ReactNode
}) {
  return (
    <section className={cn('grid content-start gap-5 rounded-[1.5rem] border bg-card p-5 shadow-deep sm:p-6', className)}>
      <header className="flex items-start justify-between gap-4">
        <div className="flex items-start gap-3">
          <span className="grid size-9 shrink-0 place-items-center rounded-xl bg-gradient-to-br from-primary/15 to-[var(--gold-glow)]/25 text-primary ring-1 ring-primary/15 ring-inset">
            <Icon className="size-4" aria-hidden />
          </span>
          <div>
            <h2 className="text-lg font-bold">{title}</h2>
            {sub && <p className="text-sm text-muted-foreground">{sub}</p>}
          </div>
        </div>
        {action}
      </header>
      {children}
    </section>
  )
}

const viewAllClass =
  'group inline-flex shrink-0 items-center gap-1 rounded-full border px-3 py-1 text-xs font-medium text-primary transition-colors hover:bg-primary hover:text-primary-foreground'

function ViewAll({ to }: { to: '/admin/payments' | '/admin/messages' | '/admin/customers' }) {
  const label = (
    <>
      View all <ArrowRight className="size-3 transition-transform group-hover:translate-x-0.5" aria-hidden />
    </>
  )
  return to === '/admin/customers' ? (
    <Link to={to} className={viewAllClass}>
      {label}
    </Link>
  ) : (
    <Link to={to} search={{ status: 'all' }} className={viewAllClass}>
      {label}
    </Link>
  )
}

function plural(n: number, word: string) {
  return n === 1 ? word : `${word}s`
}

function OverviewSkeleton() {
  return (
    <div className="grid gap-8" aria-busy="true">
      <Skeleton className="h-96 rounded-[2rem]" />
      <div className="grid gap-4 sm:grid-cols-2 xl:grid-cols-4">
        {Array.from({ length: 4 }, (_, i) => (
          <Skeleton key={i} className="h-44 rounded-2xl" />
        ))}
      </div>
      <div className="grid gap-6 lg:grid-cols-3">
        <Skeleton className="h-80 rounded-[1.5rem] lg:col-span-2" />
        <Skeleton className="h-80 rounded-[1.5rem]" />
      </div>
    </div>
  )
}
