'use client';

import { ChevronRight, Search, X } from 'lucide-react';
import { useState } from 'react';
import { useQuery } from '@tanstack/react-query';

import { NoResultsIllustration } from '@/components/illustrations';
import { PageHeader } from '@/components/layout/page-header';
import { Card } from '@/components/ui/card';
import { CopyButton } from '@/components/ui/copy-button';
import { Input } from '@/components/ui/input';
import { JsonBlock } from '@/components/ui/json-block';
import { Drawer } from '@/components/ui/overlay';
import { EmptyState, ErrorState } from '@/components/ui/states';
import { Skeleton } from '@/components/ui/skeleton';
import { ApiError, apiEnvelope } from '@/lib/api-client';
import { formatRelative } from '@/lib/shipments';
import { cn } from '@/lib/utils';

interface AuditRow {
  id: string;
  tenantId: string | null;
  userId: string | null;
  action: string;
  metadata: Record<string, unknown>;
  createdAt: string;
}

/** Colors an action badge by its verb so destructive actions stand out. */
const actionTone = (action: string) =>
  /delete|revoke|suspend|reject|disable|debit/i.test(action)
    ? 'bg-danger-soft text-danger'
    : /create|invite|enable|reactivate|credit|paid/i.test(action)
      ? 'bg-success-soft text-success'
      : 'bg-surface-muted text-foreground';

const metaIp = (metadata: Record<string, unknown>): string | null => {
  const ip = metadata.ip ?? metadata.ipAddress;
  return typeof ip === 'string' && ip.length > 0 ? ip : null;
};

function IdCell({ value }: { value: string | null }) {
  if (value === null) return <span className="text-subtle-foreground">—</span>;
  return (
    <span className="block max-w-[140px] truncate font-mono text-caption text-muted-foreground" title={value}>
      {value}
    </span>
  );
}

export default function AdminAuditPage() {
  const [action, setAction] = useState('');
  const [selected, setSelected] = useState<AuditRow | null>(null);
  const query = `?page=1&pageSize=50${action.trim() ? `&action=${encodeURIComponent(action.trim())}` : ''}`;
  const list = useQuery({
    queryKey: ['admin', 'audit', query],
    queryFn: () => apiEnvelope<{ data: AuditRow[] }>(`/admin/audit${query}`),
  });
  const rows = list.data?.data ?? [];
  const selectedIp = selected === null ? null : metaIp(selected.metadata);

  return (
    <div className="grid gap-5">
      <PageHeader title="Audit log" description="Sensitive platform and tenant actions." />
      <Card className="p-3">
        <Input type="search" aria-label="Filter by action" leading={<Search />} className="font-mono text-small" value={action} placeholder="Filter by action, e.g. wallet.adjust" onChange={(event) => setAction(event.target.value)} />
      </Card>
      {list.isLoading ? (
        <Card className="overflow-hidden p-0" aria-hidden="true">
          {Array.from({ length: 8 }, (_, index) => (
            <div key={index} className="flex h-14 items-center gap-4 border-b border-border px-5 last:border-b-0">
              <Skeleton className="h-4 w-20" />
              <Skeleton className="h-5 w-36 rounded-pill" />
              <Skeleton className="ml-auto h-4 w-24" />
            </div>
          ))}
        </Card>
      ) : 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={<NoResultsIllustration size={110} />} title={action.trim() ? 'No entries match this action' : 'No audit entries yet'} />
        </Card>
      ) : null}
      {rows.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">Time</th>
                  <th scope="col" className="px-3 font-semibold">Action</th>
                  <th scope="col" className="px-3 font-semibold">Actor</th>
                  <th scope="col" className="px-3 font-semibold">Tenant</th>
                  <th scope="col" className="w-12 pr-4">
                    <span className="sr-only">Open</span>
                  </th>
                </tr>
              </thead>
              <tbody>
                {rows.map((row) => (
                  <tr
                    key={row.id}
                    tabIndex={0}
                    aria-label={`Open ${row.action} entry`}
                    className="group h-14 cursor-pointer border-b border-border transition-colors last:border-b-0 hover:bg-surface-muted/60 focus-visible:bg-surface-muted/60 focus-visible:outline-none"
                    onClick={() => setSelected(row)}
                    onKeyDown={(event) => {
                      if (event.key === 'Enter' || event.key === ' ') {
                        event.preventDefault();
                        setSelected(row);
                      }
                    }}
                  >
                    <td className="whitespace-nowrap pl-5 pr-3 text-muted-foreground" title={new Date(row.createdAt).toLocaleString()}>
                      {formatRelative(row.createdAt)}
                    </td>
                    <td className="px-3">
                      <span className={cn('inline-block whitespace-nowrap rounded-md px-2 py-0.5 font-mono text-caption font-semibold', actionTone(row.action))}>{row.action}</span>
                    </td>
                    <td className="px-3">
                      <IdCell value={row.userId} />
                    </td>
                    <td className="px-3">
                      <IdCell value={row.tenantId} />
                    </td>
                    <td className="pr-4">
                      <ChevronRight className="h-4 w-4 text-subtle-foreground transition-transform group-hover:translate-x-0.5" aria-hidden="true" />
                    </td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        </Card>
      ) : null}

      <Drawer open={selected !== null} title={selected?.action ?? 'Audit entry'} side="right" onClose={() => setSelected(null)} className="flex flex-col p-0">
        {selected === null ? null : (
          <>
            <div className="flex items-start justify-between gap-3 border-b border-border px-6 py-4">
              <div className="min-w-0">
                <h2 className={cn('inline-block rounded-md px-2 py-0.5 font-mono text-small font-semibold', actionTone(selected.action))}>{selected.action}</h2>
                <p className="mt-1.5 text-caption text-muted-foreground">{new Date(selected.createdAt).toLocaleString()}</p>
              </div>
              <button type="button" aria-label="Close" onClick={() => setSelected(null)} className="grid h-9 w-9 shrink-0 place-items-center rounded-md text-muted-foreground hover:bg-surface-muted hover:text-foreground">
                <X className="h-4 w-4" aria-hidden="true" />
              </button>
            </div>
            <div className="grid flex-1 content-start gap-5 overflow-y-auto px-6 py-5">
              <dl className="grid gap-3 text-small">
                {[
                  { label: 'Actor', value: selected.userId },
                  { label: 'Tenant', value: selected.tenantId },
                  { label: 'IP address', value: selectedIp },
                ].map((item) =>
                  item.value === null ? null : (
                    <div key={item.label} className="flex items-center justify-between gap-3">
                      <dt className="text-muted-foreground">{item.label}</dt>
                      <dd className="flex min-w-0 items-center gap-1 font-mono text-caption">
                        <span className="truncate">{item.value}</span>
                        <CopyButton notify value={item.value} label={`Copy ${item.label.toLowerCase()}`} />
                      </dd>
                    </div>
                  ),
                )}
              </dl>
              <div className="grid gap-2">
                <h3 className="text-caption font-semibold uppercase tracking-[0.08em] text-muted-foreground">Metadata</h3>
                <JsonBlock value={selected.metadata} label="Copy metadata" />
              </div>
            </div>
          </>
        )}
      </Drawer>
    </div>
  );
}
