import { useState, type FormEvent } from 'react'
import { createFileRoute, Link, useNavigate, useRouter } from '@tanstack/react-router'
import { useServerFn } from '@tanstack/react-start'
import { Coins, History, MessageCircle, Search, Users, Wallet } from 'lucide-react'
import { toast } from 'sonner'
import { z } from 'zod'
import { Button } from '@/components/ui/button'
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogFooter,
  DialogHeader,
  DialogTitle,
} from '@/components/ui/dialog'
import { Input } from '@/components/ui/input'
import { Label } from '@/components/ui/label'
import { RadioGroup, RadioGroupItem } from '@/components/ui/radio-group'
import { Skeleton } from '@/components/ui/skeleton'
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from '@/components/ui/table'
import { Avatar, CustomerCell, EmptyState, Panel, PageIntro, SummaryStrip, dateFormat, timeAgo } from '@/components/admin/AdminUi'
import { adjustCredits, getCustomers } from '@/lib/admin.functions'
import { formatCedis } from '@/lib/pricing'

export const Route = createFileRoute('/admin/customers')({
  validateSearch: z.object({ q: z.string().max(200).optional().catch(undefined) }),
  loaderDeps: ({ search }) => ({ q: search.q }),
  loader: ({ deps }) => getCustomers({ data: { q: deps.q } }),
  head: () => ({ meta: [{ title: 'Admin · Customers — AkotoCreative SMS' }] }),
  pendingComponent: CustomersSkeleton,
  component: CustomersPage,
})

type Customer = Awaited<ReturnType<typeof getCustomers>>['customers'][number]

function CustomersPage() {
  const { q } = Route.useSearch()
  const data = Route.useLoaderData()
  const navigate = useNavigate({ from: Route.fullPath })
  const [query, setQuery] = useState(q ?? '')
  const [adjusting, setAdjusting] = useState<Customer | null>(null)

  function search(event: FormEvent) {
    event.preventDefault()
    navigate({ search: { q: query.trim() || undefined } })
  }

  return (
    <div className="grid gap-8">
      <PageIntro eyebrow="People" title="Customers">
        Everyone who has signed in to AkotoCreative SMS, with their balance and spending. Use “Adjust credit” for refunds, goodwill
        top-ups or corrections. Every change is recorded below.
      </PageIntro>

      <SummaryStrip
        items={[
          { label: q ? 'Matching' : 'Customers shown', value: data.customers.length.toLocaleString(), icon: Users },
          {
            label: 'Credit held',
            value: data.customers.reduce((sum, c) => sum + c.credits, 0).toLocaleString(),
            icon: Wallet,
            tone: 'gold',
          },
          { label: 'Total paid', value: formatCedis(data.customers.reduce((sum, c) => sum + c.spent, 0)), icon: Coins },
          {
            label: 'SMS sent',
            value: data.customers.reduce((sum, c) => sum + c.smsSent, 0).toLocaleString(),
            icon: History,
          },
        ]}
      />

      <form
        onSubmit={search}
        role="search"
        className="flex max-w-xl items-center gap-2 rounded-2xl border bg-card p-1.5 shadow-deep focus-within:ring-2 focus-within:ring-ring/40"
      >
        <Label htmlFor="customer-search" className="sr-only">
          Search by email
        </Label>
        <Search className="ml-2 size-4 shrink-0 text-muted-foreground" aria-hidden />
        <Input
          id="customer-search"
          type="search"
          value={query}
          onChange={(e) => setQuery(e.target.value)}
          placeholder="Search customers by email"
          maxLength={200}
          className="border-0 bg-transparent shadow-none focus-visible:ring-0"
        />
        <Button type="submit" className="rounded-xl">
          Search
        </Button>
      </form>

      {data.customers.length === 0 ? (
        <EmptyState icon={Users}>{q ? `No customers match “${q}”.` : 'No customers yet.'}</EmptyState>
      ) : (
        <Panel>
          <Table>
            <TableHeader>
              <TableRow>
                <TableHead>Customer</TableHead>
                <TableHead>Joined</TableHead>
                <TableHead className="text-right">Balance</TableHead>
                <TableHead className="text-right">Paid</TableHead>
                <TableHead className="text-right">SMS sent</TableHead>
                <TableHead>Last send</TableHead>
                <TableHead>
                  <span className="sr-only">Actions</span>
                </TableHead>
              </TableRow>
            </TableHeader>
            <TableBody>
              {data.customers.map((c) => (
                <TableRow key={c.userId}>
                  <TableCell>
                    <CustomerCell email={c.email || 'No email'} />
                  </TableCell>
                  <TableCell className="whitespace-nowrap text-muted-foreground">
                    {dateFormat.format(new Date(c.createdAt))}
                  </TableCell>
                  <TableCell className="text-right">
                    <span
                      className={
                        c.credits > 0
                          ? 'rounded-full bg-primary/10 px-2.5 py-1 font-semibold text-primary tabular-nums'
                          : 'font-semibold text-muted-foreground tabular-nums'
                      }
                    >
                      {c.credits.toLocaleString()}
                    </span>
                  </TableCell>
                  <TableCell className="text-right tabular-nums">{formatCedis(c.spent)}</TableCell>
                  <TableCell className="text-right tabular-nums">{c.smsSent.toLocaleString()}</TableCell>
                  <TableCell className="whitespace-nowrap text-muted-foreground">
                    {c.lastSendAt ? (
                      <span title={dateFormat.format(new Date(c.lastSendAt))}>{timeAgo(c.lastSendAt)}</span>
                    ) : (
                      '—'
                    )}
                  </TableCell>
                  <TableCell className="text-right">
                    <div className="flex justify-end gap-2">
                      <Button size="sm" variant="outline" asChild>
                        <Link to="/admin/chat" search={{ user: c.userId }}>
                          <MessageCircle /> Message
                        </Link>
                      </Button>
                      <Button size="sm" variant="outline" onClick={() => setAdjusting(c)}>
                        <Coins /> Adjust credit
                      </Button>
                    </div>
                  </TableCell>
                </TableRow>
              ))}
            </TableBody>
          </Table>
        </Panel>
      )}

      <section aria-labelledby="adjustments-heading">
        <h2 id="adjustments-heading" className="mb-3 flex items-center gap-2 text-xl font-bold">
          <History className="size-5 text-primary" aria-hidden />
          Recent credit adjustments
        </h2>
        {data.adjustments.length === 0 ? (
          <EmptyState icon={History}>No manual adjustments yet.</EmptyState>
        ) : (
          <Panel>
            <Table>
              <TableHeader>
                <TableRow>
                  <TableHead>Date</TableHead>
                  <TableHead>Customer</TableHead>
                  <TableHead className="text-right">Credits</TableHead>
                  <TableHead>Reason</TableHead>
                  <TableHead>By</TableHead>
                </TableRow>
              </TableHeader>
              <TableBody>
                {data.adjustments.map((a) => (
                  <TableRow key={a.id}>
                    <TableCell className="whitespace-nowrap">{dateFormat.format(new Date(a.createdAt))}</TableCell>
                    <TableCell>
                      <CustomerCell email={a.email} />
                    </TableCell>
                    <TableCell className="text-right">
                      <span
                        className={`rounded-full px-2.5 py-1 font-semibold tabular-nums ${a.amount < 0 ? 'bg-destructive/10 text-destructive' : 'bg-primary/10 text-primary'}`}
                      >
                        {a.amount > 0 ? '+' : '−'}
                        {Math.abs(a.amount).toLocaleString()}
                      </span>
                    </TableCell>
                    <TableCell className="max-w-xs truncate" title={a.reason}>
                      {a.reason}
                    </TableCell>
                    <TableCell className="max-w-48 truncate text-muted-foreground">{a.adminEmail}</TableCell>
                  </TableRow>
                ))}
              </TableBody>
            </Table>
          </Panel>
        )}
      </section>

      <AdjustDialog customer={adjusting} onClose={() => setAdjusting(null)} />
    </div>
  )
}

function AdjustDialog({ customer, onClose }: { customer: Customer | null; onClose: () => void }) {
  const router = useRouter()
  const adjust = useServerFn(adjustCredits)
  const [direction, setDirection] = useState<'add' | 'remove'>('add')
  const [amount, setAmount] = useState('')
  const [reason, setReason] = useState('')
  const [saving, setSaving] = useState(false)

  function close() {
    if (saving) return
    setDirection('add')
    setAmount('')
    setReason('')
    onClose()
  }

  async function submit(event: FormEvent) {
    event.preventDefault()
    if (!customer) return
    const credits = Number(amount)
    if (!Number.isInteger(credits) || credits <= 0) {
      toast.error('Enter a whole number of credits.')
      return
    }
    setSaving(true)
    try {
      const result = await adjust({
        data: { userId: customer.userId, amount: direction === 'add' ? credits : -credits, reason: reason.trim() },
      })
      toast.success(`${customer.email} now has ${result.credits.toLocaleString()} credits.`)
      await router.invalidate()
      setSaving(false)
      close()
    } catch (err) {
      toast.error(err instanceof Error ? err.message : 'The balance could not be changed.')
      setSaving(false)
    }
  }

  return (
    <Dialog open={customer !== null} onOpenChange={(open) => !open && close()}>
      <DialogContent>
        <form onSubmit={submit} className="grid gap-5">
          <DialogHeader>
            <DialogTitle>Adjust credit</DialogTitle>
            <DialogDescription asChild>
              <div className="flex items-center gap-3 rounded-xl bg-muted/60 p-3">
                <Avatar email={customer?.email} className="size-10" />
                <div className="min-w-0">
                  <p className="truncate font-medium text-foreground">{customer?.email}</p>
                  <p>
                    Current balance:{' '}
                    <span className="font-semibold text-foreground tabular-nums">{customer?.credits.toLocaleString()}</span>{' '}
                    credits
                  </p>
                </div>
              </div>
            </DialogDescription>
          </DialogHeader>

          <RadioGroup
            value={direction}
            onValueChange={(v) => setDirection(v as 'add' | 'remove')}
            className="grid grid-cols-2 gap-2"
            aria-label="Add or remove credits"
          >
            {(['add', 'remove'] as const).map((value) => (
              <Label
                key={value}
                htmlFor={`direction-${value}`}
                className="flex cursor-pointer items-center gap-2 rounded-lg border px-3 py-2.5 has-[[data-state=checked]]:border-primary has-[[data-state=checked]]:bg-primary/5"
              >
                <RadioGroupItem id={`direction-${value}`} value={value} />
                {value === 'add' ? 'Add credits' : 'Remove credits'}
              </Label>
            ))}
          </RadioGroup>

          <div className="grid gap-2">
            <Label htmlFor="adjust-amount">Credits</Label>
            <Input
              id="adjust-amount"
              type="number"
              inputMode="numeric"
              min={1}
              max={direction === 'remove' ? customer?.credits : 1_000_000}
              step={1}
              required
              value={amount}
              onChange={(e) => setAmount(e.target.value)}
            />
          </div>

          <div className="grid gap-2">
            <Label htmlFor="adjust-reason">Reason</Label>
            <Input
              id="adjust-reason"
              required
              minLength={3}
              maxLength={300}
              value={reason}
              onChange={(e) => setReason(e.target.value)}
              placeholder="e.g. Refund for failed send on 12 Oct"
            />
          </div>

          <DialogFooter>
            <Button type="button" variant="ghost" onClick={close} disabled={saving}>
              Cancel
            </Button>
            <Button type="submit" disabled={saving}>
              {saving ? 'Saving…' : direction === 'add' ? 'Add credits' : 'Remove credits'}
            </Button>
          </DialogFooter>
        </form>
      </DialogContent>
    </Dialog>
  )
}

function CustomersSkeleton() {
  return (
    <div className="grid gap-8" aria-busy="true">
      <Skeleton className="h-10 w-56" />
      <div className="grid gap-3 sm:grid-cols-2 lg:grid-cols-4">
        {Array.from({ length: 4 }, (_, i) => (
          <Skeleton key={i} className="h-20 rounded-2xl" />
        ))}
      </div>
      <Skeleton className="h-12 max-w-xl rounded-2xl" />
      <Skeleton className="h-80 rounded-2xl" />
    </div>
  )
}
