'use client';

import { ArrowDownToLine, CalendarCheck, ChevronLeft, ChevronRight, Clock, Download, LoaderCircle, Plus, Wallet as WalletIcon, type LucideIcon } from 'lucide-react';
import Link from 'next/link';
import { useSearchParams } from 'next/navigation';
import { Suspense, useEffect, useMemo, useState } from 'react';
import { useQuery, useQueryClient } from '@tanstack/react-query';
import { toast } from 'sonner';

import { EmptyBoxIllustration } from '@/components/illustrations';
import { SuccessBurst } from '@/components/illustrations/success-burst';
import { PageHeader } from '@/components/layout/page-header';
import { TopUpModal } from '@/components/shipments/top-up-modal';
import { DateRangePopover } from '@/components/tables/date-range-picker';
import { Button } from '@/components/ui/button';
import { Card } from '@/components/ui/card';
import { CopyButton } from '@/components/ui/copy-button';
import { Select } from '@/components/ui/input';
import { DateText } from '@/components/ui/money-text';
import { EmptyState, ErrorState, ForbiddenState } from '@/components/ui/states';
import { Skeleton } from '@/components/ui/skeleton';
import { UnderlineTabs } from '@/components/ui/tabs';
import { ApiError, api, apiBlob, apiEnvelope, downloadBlob } from '@/lib/api-client';
import { formatMoney } from '@/lib/money';
import { queryKeys } from '@/lib/query-keys';
import { formatRelative } from '@/lib/shipments';
import { cn } from '@/lib/utils';
import { usePermission } from '@/hooks/use-permission';
import { LEDGER_TYPES } from '@/shared/enums';

interface WalletView {
  balanceMinor: number;
  currency: string;
  lowBalance: boolean;
  provider: 'manual' | 'stripe';
}

interface LedgerEntry {
  id: string;
  type: string;
  amountMinor: number;
  balanceAfterMinor: number;
  currency: string;
  note?: string;
  shipmentId?: string;
  createdAt: string;
}

interface TopUpRow {
  id: string;
  amountMinor: number;
  currency: string;
  provider: string;
  status: string;
  reference?: string;
  paidAt?: string;
  createdAt: string;
}

function WalletPageInner() {
  const allowed = usePermission('wallet:read');
  const canTopUp = usePermission('wallet:topup');
  const search = useSearchParams();
  const queryClient = useQueryClient();
  const [open, setOpen] = useState(false);
  const [tab, setTab] = useState<'ledger' | 'topups'>('ledger');
  const [type, setType] = useState('');
  const [dateFrom, setDateFrom] = useState('');
  const [dateTo, setDateTo] = useState('');
  const [page, setPage] = useState(1);
  const topupSuccess = search.get('topup') === 'success';

  const wallet = useQuery({
    queryKey: queryKeys.wallet,
    enabled: allowed,
    queryFn: () => api<WalletView>('/wallet'),
    refetchInterval: topupSuccess ? 3000 : false,
  });

  useEffect(() => {
    if (!topupSuccess) return undefined;
    const started = Date.now();
    const timer = window.setInterval(() => {
      if (Date.now() - started > 60_000) {
        window.clearInterval(timer);
        return;
      }
      void queryClient.invalidateQueries({ queryKey: queryKeys.wallet });
    }, 3000);
    return () => window.clearInterval(timer);
  }, [topupSuccess, queryClient]);

  // Remember the balance seen when returning from a hosted checkout, to detect the credit landing.
  const [initialBalance, setInitialBalance] = useState<number | null>(null);
  if (initialBalance === null && wallet.data !== undefined) setInitialBalance(wallet.data.balanceMinor);

  const ledgerQuery = useMemo(() => {
    const params = new URLSearchParams({ page: String(page), pageSize: '20' });
    if (type) params.set('type', type);
    if (dateFrom) params.set('dateFrom', dateFrom);
    if (dateTo) params.set('dateTo', dateTo);
    return `?${params.toString()}`;
  }, [page, type, dateFrom, dateTo]);

  const ledger = useQuery({
    queryKey: ['wallet', 'ledger', ledgerQuery],
    enabled: allowed && tab === 'ledger',
    queryFn: () => apiEnvelope<{ data: LedgerEntry[]; meta: { page: number; totalPages: number } }>(`/wallet/ledger${ledgerQuery}`),
  });

  const topups = useQuery({
    queryKey: ['wallet', 'topups'],
    enabled: allowed,
    queryFn: () => apiEnvelope<{ data: TopUpRow[]; meta: { page: number; totalPages: number } }>('/wallet/topups?page=1&pageSize=50'),
  });

  if (!allowed) return <ForbiddenState />;

  const topupRows = topups.data?.data ?? [];
  const pending = topupRows.filter((row) => row.status === 'PENDING');
  const monthStart = new Date();
  monthStart.setDate(1);
  monthStart.setHours(0, 0, 0, 0);
  const paidThisMonth = topupRows.filter((row) => row.status === 'PAID' && Date.parse(row.paidAt ?? row.createdAt) >= monthStart.getTime());
  const paidThisMonthMinor = paidThisMonth.reduce((sum, row) => sum + row.amountMinor, 0);
  const lastPaid = topupRows.find((row) => row.status === 'PAID');
  const balanceState = wallet.data === undefined ? null : wallet.data.balanceMinor <= 0 ? 'empty' : wallet.data.lowBalance ? 'low' : 'healthy';
  const credited = topupSuccess && wallet.data !== undefined && initialBalance !== null && wallet.data.balanceMinor > initialBalance;

  const downloadStatement = () => {
    void apiBlob(`/wallet/statement.csv${dateFrom || dateTo ? `?${new URLSearchParams({ ...(dateFrom ? { dateFrom } : {}), ...(dateTo ? { dateTo } : {}) }).toString()}` : ''}`, 'text/csv')
      .then((blob) => downloadBlob(blob, 'wallet-statement.csv'))
      .catch((reason: unknown) => toast.error(reason instanceof ApiError ? reason.message : 'Could not download statement.'));
  };

  return (
    <div className="grid gap-6">
      <PageHeader
        title="Wallet"
        description="Your prepaid balance, top-ups and every transaction."
        actions={
          <>
            <Button type="button" variant="secondary" onClick={downloadStatement}>
              <Download className="h-4 w-4" aria-hidden="true" />
              Download statement
            </Button>
            {canTopUp ? (
              <Button type="button" onClick={() => setOpen(true)}>
                <Plus className="h-4 w-4" aria-hidden="true" />
                Top up
              </Button>
            ) : null}
          </>
        }
      />

      {topupSuccess ? (
        credited ? (
          <div className="flex items-center gap-4 rounded-xl border border-success/25 bg-success-soft px-4 py-3" role="status">
            <SuccessBurst size={56} className="-my-2 shrink-0" />
            <div>
              <p className="font-display text-h3 font-bold">Top-up received</p>
              <p className="text-small text-muted-foreground">Your wallet has been credited.</p>
            </div>
          </div>
        ) : (
          <div className="overflow-hidden rounded-xl border border-info/25 bg-info-soft" role="status">
            <div className="flex items-center gap-3 px-4 py-3">
              <LoaderCircle className="h-5 w-5 shrink-0 animate-spin text-info" aria-hidden="true" />
              <p className="text-small">
                <span className="font-semibold">Processing your top-up.</span> <span className="text-muted-foreground">This page refreshes automatically.</span>
              </p>
            </div>
            <div className="h-1 overflow-hidden bg-info/15" aria-hidden="true">
              <div className="h-full w-full origin-left bg-info motion-safe:animate-[progress-indeterminate_1.4s_cubic-bezier(0.2,0.8,0.2,1)_infinite]" />
            </div>
          </div>
        )
      ) : null}

      <div className="grid gap-6 lg:grid-cols-3">
        {wallet.isLoading ? <Skeleton className="h-56 rounded-xl lg:col-span-2" /> : null}
        {wallet.error instanceof ApiError ? (
          <Card className="lg:col-span-2">
            <ErrorState message={wallet.error.message} requestId={wallet.error.requestId} onRetry={() => void wallet.refetch()} />
          </Card>
        ) : null}
        {wallet.data === undefined ? null : (
          <section
            aria-label="Wallet balance"
            className="relative isolate flex min-h-56 flex-col justify-between overflow-hidden rounded-xl bg-[linear-gradient(140deg,rgb(var(--ink-from)),rgb(var(--brand-to)))] p-6 text-primary-foreground shadow-md md:p-8 lg:col-span-2"
          >
            <div className="pointer-events-none absolute inset-0 -z-10 bg-mesh opacity-40 [--accent:255_255_255] [--primary:167_139_250]" aria-hidden="true" />
            <div className="pointer-events-none absolute -bottom-20 -right-16 -z-10 h-64 w-64 rounded-full border-[32px] border-primary-foreground/[0.06]" aria-hidden="true" />
            <div>
              <div className="flex flex-wrap items-center justify-between gap-3">
                <p className="flex items-center gap-2 text-[13px] font-medium text-primary-foreground/70">
                  <WalletIcon className="h-4 w-4" aria-hidden="true" />
                  Available balance
                </p>
                <span
                  className={cn(
                    'inline-flex items-center gap-1.5 rounded-pill px-2.5 py-1 text-caption font-semibold ring-1 ring-inset',
                    balanceState === 'healthy' && 'bg-success/20 text-success ring-success/30',
                    balanceState === 'low' && 'bg-warning/20 text-warning ring-warning/30',
                    balanceState === 'empty' && 'bg-danger/20 text-danger ring-danger/30',
                  )}
                >
                  <span className={cn('h-1.5 w-1.5 rounded-full', balanceState === 'healthy' ? 'bg-success' : balanceState === 'low' ? 'bg-warning' : 'bg-danger')} aria-hidden="true" />
                  {balanceState === 'healthy' ? 'Healthy' : balanceState === 'low' ? 'Low balance' : 'Empty'}
                </span>
              </div>
              <p className="mt-3 font-display text-[2.75rem] font-extrabold leading-none tracking-[-0.03em] tabular-nums md:text-display-xl">
                {formatMoney(wallet.data.balanceMinor, wallet.data.currency)}
              </p>
              {balanceState === 'low' ? <p className="mt-2 text-small text-primary-foreground/75">Below your low balance threshold. Top up to keep shipping.</p> : null}
            </div>
            <div className="mt-6 flex flex-wrap gap-2">
              {canTopUp ? (
                <Button type="button" size="sm" className="bg-primary-foreground bg-none text-[rgb(var(--ink-from))] shadow-sm hover:bg-primary-foreground/90" onClick={() => setOpen(true)}>
                  <Plus className="h-4 w-4" aria-hidden="true" />
                  Top up
                </Button>
              ) : null}
              <Button
                type="button"
                size="sm"
                variant="outline"
                className="border-primary-foreground/30 bg-primary-foreground/10 text-primary-foreground hover:bg-primary-foreground/15"
                onClick={() => setTab('topups')}
              >
                View top-ups
              </Button>
            </div>
          </section>
        )}

        <Card className="p-5 md:p-6">
          <h2 className="font-display text-h3 font-bold">This month</h2>
          <dl className="mt-4 grid gap-4">
            <Stat icon={ArrowDownToLine} tone="bg-success-soft text-success" label="Top-ups paid" value={wallet.data === undefined ? '—' : formatMoney(paidThisMonthMinor, wallet.data.currency)} />
            <Stat
              icon={Clock}
              tone="bg-warning-soft text-warning"
              label="Pending top-ups"
              value={wallet.data === undefined ? '—' : pending.length === 0 ? 'None' : `${pending.length} · ${formatMoney(pending.reduce((sum, row) => sum + row.amountMinor, 0), wallet.data.currency)}`}
            />
            <Stat icon={CalendarCheck} tone="bg-info-soft text-info" label="Last top-up" value={lastPaid === undefined ? 'None yet' : new Date(lastPaid.paidAt ?? lastPaid.createdAt).toLocaleDateString(undefined, { month: 'short', day: 'numeric' })} />
          </dl>
        </Card>
      </div>

      {pending.length === 0 ? null : (
        <section className="overflow-hidden rounded-xl border border-warning/30 bg-surface shadow-xs" aria-labelledby="pending-title">
          <header className="flex items-center gap-2 border-b border-warning/20 bg-warning-soft px-5 py-3">
            <Clock className="h-4 w-4 text-warning" aria-hidden="true" />
            <h2 id="pending-title" className="text-small font-semibold">
              Pending top-ups
            </h2>
          </header>
          <ul className="divide-y divide-border">
            {pending.map((row) => (
              <li key={row.id} className="flex flex-wrap items-center gap-x-4 gap-y-2 px-5 py-3">
                <p className="font-display text-h3 font-bold tabular-nums">{formatMoney(row.amountMinor, row.currency)}</p>
                <p className="text-caption text-muted-foreground">
                  {row.provider === 'manual' ? 'Bank transfer' : 'Card'} · {formatRelative(row.createdAt)}
                </p>
                <span className="rounded-pill bg-warning-soft px-2.5 py-0.5 text-caption font-semibold text-warning">Awaiting confirmation</span>
                {row.provider === 'manual' && row.reference !== undefined ? (
                  <span className="ml-auto flex items-center gap-1 rounded-md border border-border bg-surface-muted py-0.5 pl-2.5 pr-0.5 font-mono text-small font-semibold">
                    {row.reference}
                    <CopyButton notify value={row.reference} label="Copy payment reference" />
                  </span>
                ) : null}
                {row.provider === 'manual' && canTopUp ? (
                  <button type="button" className="text-small font-semibold text-primary underline-offset-4 hover:underline" onClick={() => setOpen(true)}>
                    View instructions
                  </button>
                ) : null}
              </li>
            ))}
          </ul>
        </section>
      )}

      <div className="grid gap-4">
        <UnderlineTabs
          label="Wallet history"
          value={tab}
          onChange={setTab}
          tabs={[
            { value: 'ledger', label: 'Ledger' },
            { value: 'topups', label: 'Top-ups', count: pending.length },
          ]}
        />

        {tab === 'ledger' ? (
          <div className="grid gap-4">
            <div className="flex flex-wrap items-center gap-2">
              <Select
                aria-label="Transaction type"
                className="h-10 min-h-10 w-auto min-w-44 text-small"
                value={type}
                onChange={(event) => {
                  setType(event.target.value);
                  setPage(1);
                }}
              >
                <option value="">All types</option>
                {LEDGER_TYPES.map((value) => (
                  <option key={value} value={value}>
                    {ledgerLabel(value)}
                  </option>
                ))}
              </Select>
              <DateRangePopover
                dateFrom={dateFrom}
                dateTo={dateTo}
                onChange={(next) => {
                  setDateFrom(next.dateFrom);
                  setDateTo(next.dateTo);
                  setPage(1);
                }}
              />
            </div>
            {ledger.isLoading ? (
              <Card className="overflow-hidden p-0" aria-hidden="true">
                {Array.from({ length: 6 }, (_, index) => (
                  <div key={index} className="flex h-14 items-center gap-6 border-b border-border px-5 last:border-b-0">
                    <Skeleton className="h-4 w-24" />
                    <Skeleton className="h-5 w-20 rounded-pill" />
                    <Skeleton className="h-4 flex-1" />
                    <Skeleton className="h-4 w-16" />
                  </div>
                ))}
              </Card>
            ) : null}
            {ledger.error instanceof ApiError ? (
              <Card>
                <ErrorState message={ledger.error.message} requestId={ledger.error.requestId} onRetry={() => void ledger.refetch()} />
              </Card>
            ) : null}
            {ledger.data !== undefined && ledger.data.data.length === 0 ? (
              <Card>
                <EmptyState
                  illustration={<EmptyBoxIllustration size={110} />}
                  title="No transactions yet"
                  description={type || dateFrom || dateTo ? 'Nothing matches these filters.' : 'Top-ups, label charges and refunds will appear here.'}
                />
              </Card>
            ) : null}
            {ledger.data !== undefined && ledger.data.data.length > 0 ? (
              <>
                <Card className="overflow-hidden p-0">
                  <div className="overflow-x-auto">
                    <table className="w-full min-w-[720px] text-left text-small">
                      <thead>
                        <tr className="h-11 border-b border-border bg-surface-muted/80 text-caption font-semibold uppercase tracking-[0.08em] text-muted-foreground">
                          <th scope="col" className="pl-5 pr-3 font-semibold">Date</th>
                          <th scope="col" className="px-3 font-semibold">Type</th>
                          <th scope="col" className="px-3 font-semibold">Description</th>
                          <th scope="col" className="px-3 text-right font-semibold">Amount</th>
                          <th scope="col" className="pl-3 pr-5 text-right font-semibold">Balance after</th>
                        </tr>
                      </thead>
                      <tbody>
                        {ledger.data.data.map((entry) => {
                          const look = ledgerLook(entry.type);
                          const credit = entry.amountMinor >= 0;
                          return (
                            <tr key={entry.id} className="relative h-14 border-b border-border last:border-b-0 hover:bg-surface-muted/60">
                              <td className="relative whitespace-nowrap pl-5 pr-3">
                                <span className={cn('absolute inset-y-2 left-0 w-[3px] rounded-r-full', look.accent)} aria-hidden="true" />
                                <span className="block text-foreground">{new Date(entry.createdAt).toLocaleDateString(undefined, { month: 'short', day: 'numeric', year: 'numeric' })}</span>
                                <span className="block text-caption text-muted-foreground">{new Date(entry.createdAt).toLocaleTimeString(undefined, { hour: '2-digit', minute: '2-digit' })}</span>
                              </td>
                              <td className="px-3">
                                <span className={cn('inline-flex rounded-pill px-2.5 py-0.5 text-caption font-semibold', look.badge)}>{ledgerLabel(entry.type)}</span>
                              </td>
                              <td className="max-w-[280px] truncate px-3">
                                {entry.shipmentId === undefined ? (
                                  <span className="text-muted-foreground">{entry.note ?? '—'}</span>
                                ) : (
                                  <Link href={`/shipments/${entry.shipmentId}`} className="font-medium text-primary underline-offset-4 hover:underline">
                                    {entry.note ?? 'Shipment'}
                                  </Link>
                                )}
                              </td>
                              <td className={cn('whitespace-nowrap px-3 text-right font-semibold tabular-nums', credit ? 'text-success' : 'text-foreground')}>
                                {credit ? '+' : '−'}
                                {formatMoney(Math.abs(entry.amountMinor), entry.currency)}
                              </td>
                              <td className="whitespace-nowrap pl-3 pr-5 text-right tabular-nums text-muted-foreground">{formatMoney(entry.balanceAfterMinor, entry.currency)}</td>
                            </tr>
                          );
                        })}
                      </tbody>
                    </table>
                  </div>
                </Card>
                <div className="flex items-center justify-between gap-3">
                  <p className="text-small text-muted-foreground">
                    Page {ledger.data.meta.page} of {ledger.data.meta.totalPages || 1}
                  </p>
                  <div className="flex gap-1">
                    <Button type="button" size="sm" variant="secondary" disabled={page <= 1} onClick={() => setPage((current) => current - 1)}>
                      <ChevronLeft className="h-4 w-4" aria-hidden="true" />
                      Previous
                    </Button>
                    <Button type="button" size="sm" variant="secondary" disabled={page >= (ledger.data.meta.totalPages || 1)} onClick={() => setPage((current) => current + 1)}>
                      Next
                      <ChevronRight className="h-4 w-4" aria-hidden="true" />
                    </Button>
                  </div>
                </div>
              </>
            ) : null}
          </div>
        ) : (
          <Card className="overflow-hidden p-0">
            {topups.isLoading ? <Skeleton className="m-5 h-40" /> : null}
            {topups.error instanceof ApiError ? <ErrorState message={topups.error.message} requestId={topups.error.requestId} onRetry={() => void topups.refetch()} /> : null}
            {topups.data !== undefined && topupRows.length === 0 ? (
              <EmptyState compact illustration={<EmptyBoxIllustration size={80} />} title="No top-ups yet" description="Add funds to start buying labels." />
            ) : null}
            {topupRows.length > 0 ? (
              <div className="overflow-x-auto">
                <table className="w-full min-w-[720px] text-left text-small">
                  <thead>
                    <tr className="h-11 border-b border-border bg-surface-muted/80 text-caption font-semibold uppercase tracking-[0.08em] text-muted-foreground">
                      <th scope="col" className="pl-5 pr-3 font-semibold">Created</th>
                      <th scope="col" className="px-3 text-right font-semibold">Amount</th>
                      <th scope="col" className="px-3 font-semibold">Method</th>
                      <th scope="col" className="px-3 font-semibold">Status</th>
                      <th scope="col" className="px-3 font-semibold">Paid at</th>
                      <th scope="col" className="pl-3 pr-5 font-semibold">Reference</th>
                    </tr>
                  </thead>
                  <tbody>
                    {topupRows.map((row) => (
                      <tr key={row.id} className="h-14 border-b border-border last:border-b-0">
                        <td className="whitespace-nowrap pl-5 pr-3">
                          <DateText value={row.createdAt} />
                        </td>
                        <td className="px-3 text-right font-semibold tabular-nums">{formatMoney(row.amountMinor, row.currency)}</td>
                        <td className="px-3 text-muted-foreground">{row.provider === 'manual' ? 'Bank transfer' : row.provider === 'stripe' ? 'Card' : row.provider}</td>
                        <td className="px-3">
                          <TopUpStatus status={row.status} />
                        </td>
                        <td className="whitespace-nowrap px-3 text-muted-foreground">{row.paidAt === undefined ? '—' : <DateText value={row.paidAt} />}</td>
                        <td className="pl-3 pr-5 font-mono text-caption">{row.reference ?? '—'}</td>
                      </tr>
                    ))}
                  </tbody>
                </table>
              </div>
            ) : null}
          </Card>
        )}
      </div>

      {wallet.data === undefined ? null : <TopUpModal open={open} currency={wallet.data.currency} provider={wallet.data.provider} onClose={() => setOpen(false)} />}
    </div>
  );
}

function Stat({ icon: Icon, tone, label, value }: { icon: LucideIcon; tone: string; label: string; value: string }) {
  return (
    <div className="flex items-center gap-3">
      <span className={cn('grid h-9 w-9 shrink-0 place-items-center rounded-lg', tone)}>
        <Icon className="h-[18px] w-[18px]" aria-hidden="true" />
      </span>
      <div className="min-w-0">
        <dt className="text-caption text-muted-foreground">{label}</dt>
        <dd className="truncate font-display text-h3 font-bold tabular-nums">{value}</dd>
      </div>
    </div>
  );
}

const ledgerLabel = (type: string): string =>
  ({ TOPUP: 'Top-up', SHIPMENT_DEBIT: 'Shipment', SHIPMENT_REFUND: 'Refund', ADJUSTMENT: 'Adjustment' })[type] ?? type.replaceAll('_', ' ').toLowerCase();

const ledgerLook = (type: string): { badge: string; accent: string } => {
  if (type === 'TOPUP') return { badge: 'bg-success-soft text-success', accent: 'bg-success' };
  if (type === 'SHIPMENT_REFUND') return { badge: 'bg-info-soft text-info', accent: 'bg-info' };
  if (type === 'ADJUSTMENT') return { badge: 'bg-warning-soft text-warning', accent: 'bg-warning' };
  return { badge: 'bg-surface-muted text-muted-foreground', accent: 'bg-border-strong' };
};

function TopUpStatus({ status }: { status: string }) {
  const look =
    status === 'PAID'
      ? { label: 'Paid', className: 'bg-success-soft text-success', dot: 'bg-success' }
      : status === 'PENDING'
        ? { label: 'Pending', className: 'bg-warning-soft text-warning', dot: 'bg-warning' }
        : status === 'FAILED'
          ? { label: 'Failed', className: 'bg-danger-soft text-danger', dot: 'bg-danger' }
          : { label: status === 'CANCELLED' ? 'Cancelled' : status, className: 'bg-surface-muted text-muted-foreground', dot: 'bg-subtle-foreground' };
  return (
    <span className={cn('inline-flex items-center gap-1.5 rounded-pill px-2.5 py-0.5 text-caption font-semibold', look.className)}>
      <span className={cn('h-1.5 w-1.5 rounded-full', look.dot)} aria-hidden="true" />
      {look.label}
    </span>
  );
}

export default function WalletPage() {
  return (
    <Suspense fallback={<Skeleton className="h-64" />}>
      <WalletPageInner />
    </Suspense>
  );
}
