'use client';

import { Check, Clock, X } from 'lucide-react';
import { useState } from 'react';
import { useQuery, useQueryClient } from '@tanstack/react-query';
import { toast } from 'sonner';

import { EmptyBoxIllustration } from '@/components/illustrations';
import { PageHeader } from '@/components/layout/page-header';
import { Avatar } from '@/components/ui/avatar';
import { Button } from '@/components/ui/button';
import { Card } from '@/components/ui/card';
import { ConfirmDialog } from '@/components/ui/confirm-dialog';
import { CopyButton } from '@/components/ui/copy-button';
import { ReasonDialog } from '@/components/ui/reason-dialog';
import { EmptyState, ErrorState } from '@/components/ui/states';
import { Skeleton } from '@/components/ui/skeleton';
import { UnderlineTabs } from '@/components/ui/tabs';
import { ApiError, api, apiEnvelope } from '@/lib/api-client';
import { formatMoney } from '@/lib/money';
import { formatRelative } from '@/lib/shipments';
import { cn } from '@/lib/utils';

interface TopUpRow {
  id: string;
  tenantName: string;
  amountMinor: number;
  currency: string;
  reference: string | null;
  status: string;
  createdAt: string;
}

const statusLook = (status: string) =>
  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.charAt(0) + status.slice(1).toLowerCase(), className: 'bg-surface-muted text-muted-foreground', dot: 'bg-subtle-foreground' };

export default function AdminTopUpsPage() {
  const queryClient = useQueryClient();
  const [tab, setTab] = useState<'PENDING' | 'PROCESSED'>('PENDING');
  const [rejectTarget, setRejectTarget] = useState<TopUpRow | null>(null);
  const [rejectReason, setRejectReason] = useState('');
  const [rejectError, setRejectError] = useState<string | null>(null);
  const [payTarget, setPayTarget] = useState<TopUpRow | null>(null);
  const list = useQuery({
    queryKey: ['admin', 'topups', tab],
    queryFn: () => apiEnvelope<{ data: TopUpRow[] }>(`/admin/topups?page=1&pageSize=50&status=${tab}`),
  });
  // Same request the Pending tab makes; used for the tab count badge.
  const pendingList = useQuery({
    queryKey: ['admin', 'topups', 'PENDING'],
    queryFn: () => apiEnvelope<{ data: TopUpRow[] }>('/admin/topups?page=1&pageSize=50&status=PENDING'),
  });
  const rows = list.data?.data ?? [];

  return (
    <div className="grid gap-5">
      <PageHeader title="Top-ups" description="Confirm or reject manual wallet top-ups." />
      <UnderlineTabs
        label="Top-up lists"
        value={tab}
        onChange={setTab}
        tabs={[
          { value: 'PENDING', label: 'Pending', count: pendingList.data?.data.length },
          { value: 'PROCESSED', label: 'History' },
        ]}
      />
      {list.isLoading ? <Skeleton className="h-64 rounded-xl" /> : null}
      {list.error instanceof ApiError ? (
        <Card>
          <ErrorState message={list.error.message} requestId={list.error.requestId} onRetry={() => void list.refetch()} />
        </Card>
      ) : null}
      {list.data !== undefined && rows.length === 0 ? (
        <Card>
          <EmptyState illustration={<EmptyBoxIllustration size={100} />} title={tab === 'PENDING' ? 'No pending top-ups' : 'No processed top-ups yet'} description={tab === 'PENDING' ? 'New bank transfer requests will show up here.' : undefined} />
        </Card>
      ) : null}
      {rows.length > 0 ? (
        <Card className="overflow-hidden p-0">
          <div className="overflow-x-auto">
            <table className="w-full min-w-[760px] 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">Tenant</th>
                  <th scope="col" className="px-3 text-right font-semibold">Amount</th>
                  <th scope="col" className="px-3 font-semibold">Reference</th>
                  <th scope="col" className="px-3 font-semibold">Created</th>
                  <th scope="col" className="px-3 font-semibold">Status</th>
                  <th scope="col" className="pl-3 pr-5 text-right font-semibold">
                    <span className="sr-only">Actions</span>
                  </th>
                </tr>
              </thead>
              <tbody>
                {rows.map((row) => {
                  const old = row.status === 'PENDING' && list.dataUpdatedAt - Date.parse(row.createdAt) > 86_400_000;
                  const look = statusLook(row.status);
                  return (
                    <tr key={row.id} className="h-16 border-b border-border last:border-b-0">
                      <td className="pl-5 pr-3">
                        <span className="flex items-center gap-3">
                          <Avatar name={row.tenantName} size="sm" shape="square" />
                          <span className="truncate font-semibold">{row.tenantName}</span>
                        </span>
                      </td>
                      <td className="whitespace-nowrap px-3 text-right font-display text-h3 font-bold tabular-nums">{formatMoney(row.amountMinor, row.currency)}</td>
                      <td className="px-3">
                        {row.reference === null ? (
                          <span className="text-subtle-foreground">—</span>
                        ) : (
                          <span className="inline-flex items-center gap-1 font-mono text-caption font-semibold">
                            {row.reference}
                            <CopyButton notify value={row.reference} label="Copy reference" />
                          </span>
                        )}
                      </td>
                      <td className="whitespace-nowrap px-3">
                        <span className="text-muted-foreground">{formatRelative(row.createdAt)}</span>
                        {old ? (
                          <span className="ml-2 inline-flex items-center gap-1 rounded-pill bg-warning-soft px-2 py-0.5 text-[11px] font-semibold text-warning">
                            <Clock className="h-3 w-3" aria-hidden="true" />
                            Over 24h
                          </span>
                        ) : null}
                      </td>
                      <td className="px-3">
                        <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>
                      </td>
                      <td className="pl-3 pr-5">
                        {row.status !== 'PENDING' ? null : (
                          <div className="flex justify-end gap-1.5">
                            <Button type="button" size="sm" className="bg-success bg-none text-primary-foreground hover:bg-success/90" onClick={() => setPayTarget(row)}>
                              <Check className="h-3.5 w-3.5" aria-hidden="true" />
                              Mark as paid
                            </Button>
                            <Button
                              type="button"
                              size="sm"
                              variant="ghost"
                              className="text-danger hover:bg-danger-soft"
                              onClick={() => {
                                setRejectError(null);
                                setRejectTarget(row);
                              }}
                            >
                              <X className="h-3.5 w-3.5" aria-hidden="true" />
                              Reject
                            </Button>
                          </div>
                        )}
                      </td>
                    </tr>
                  );
                })}
              </tbody>
            </table>
          </div>
        </Card>
      ) : null}

      <ConfirmDialog
        open={payTarget !== null}
        destructive={false}
        title="Mark this top-up as paid?"
        message={payTarget === null ? '' : `${formatMoney(payTarget.amountMinor, payTarget.currency)} will be credited to ${payTarget.tenantName}'s wallet. Only confirm once the transfer has arrived.`}
        confirmLabel="Mark as paid"
        cancelLabel="Cancel"
        onClose={() => setPayTarget(null)}
        onConfirm={() => {
          if (payTarget === null) return;
          const target = payTarget;
          setPayTarget(null);
          void api(`/admin/topups/${target.id}/mark-paid`, { method: 'POST' })
            .then(async () => {
              toast.success('Top-up marked paid.');
              await queryClient.invalidateQueries({ queryKey: ['admin', 'topups'] });
            })
            .catch((error: unknown) => toast.error(error instanceof ApiError ? error.message : 'Could not mark paid.'));
        }}
      />
      <ReasonDialog
        open={rejectTarget !== null}
        title="Reject this top-up?"
        message={rejectTarget === null ? '' : `The ${formatMoney(rejectTarget.amountMinor, rejectTarget.currency)} request from ${rejectTarget.tenantName} is cancelled without crediting the wallet.`}
        confirmLabel="Reject top-up"
        cancelLabel="Keep pending"
        reason={rejectReason}
        reasonError={rejectError}
        onReasonChange={(value) => {
          setRejectReason(value);
          setRejectError(null);
        }}
        onClose={() => setRejectTarget(null)}
        onConfirm={() => {
          if (rejectTarget === null) return;
          if (rejectReason.trim().length < 3) {
            setRejectError('Enter a rejection reason.');
            return;
          }
          void api(`/admin/topups/${rejectTarget.id}/reject`, { method: 'POST', json: { reason: rejectReason.trim() } })
            .then(async () => {
              toast.success('Top-up rejected.');
              setRejectTarget(null);
              setRejectReason('');
              await queryClient.invalidateQueries({ queryKey: ['admin', 'topups'] });
            })
            .catch((error: unknown) => toast.error(error instanceof ApiError ? error.message : 'Could not reject.'));
        }}
      />
    </div>
  );
}
