import { Fragment, useState } from 'react';
import { useQuery } from '@tanstack/react-query';
import { ChevronDown, ChevronRight } from 'lucide-react';
import { api } from '../../lib/api-client';
import { AppShell, PageHeader, PageBody } from '../../layout/AppShell';
import { Badge, Card, Input, Select } from '../../components/ui/primitives';
import { Table, THead, TBody, TR, TH, TD } from '../../components/ui/table';

interface AuditEntry {
  id: number;
  actor_email: string | null;
  actor_role: string | null;
  entity_type: string;
  entity_id: string | null;
  action: string;
  before_state: unknown;
  after_state: unknown;
  metadata: Record<string, unknown> | null;
  ip: string | null;
  created_at: string;
}

interface AuditData {
  entries: AuditEntry[];
  facets: {
    actors: string[] | null;
    entity_types: string[] | null;
    actions: string[] | null;
  };
}

const ACTION_VARIANTS: Record<string, 'success' | 'info' | 'warn' | 'danger' | 'muted'> = {
  create: 'success',
  update: 'info',
  delete: 'danger',
  enable: 'success',
  disable: 'warn',
  sync: 'info',
  regenerate: 'info',
  bulk_update: 'info',
  send: 'info',
  publish: 'success',
  reorder: 'muted',
};

export function AuditLog() {
  const [filters, setFilters] = useState({
    actor: '',
    entity_type: '',
    action: '',
    from: '',
    to: '',
  });
  const [expanded, setExpanded] = useState<Set<number>>(new Set());

  const { data } = useQuery({
    queryKey: ['audit', filters],
    queryFn: () =>
      api.get<AuditData>('/audit', {
        actor: filters.actor || undefined,
        entity_type: filters.entity_type || undefined,
        action: filters.action || undefined,
        from: filters.from || undefined,
        to: filters.to || undefined,
        limit: 200,
      }),
  });

  const entries = data?.entries ?? [];
  const facets = data?.facets ?? { actors: [], entity_types: [], actions: [] };

  const toggle = (id: number) => {
    const next = new Set(expanded);
    if (next.has(id)) next.delete(id);
    else next.add(id);
    setExpanded(next);
  };

  return (
    <AppShell>
      <PageHeader title="Audit log" description="Alle mutaties in de admin — wie, wat, wanneer." />
      <PageBody>
        <Card className="mb-4">
          <div className="px-5 py-3 grid grid-cols-5 gap-3">
            <div>
              <label className="text-xs text-[#999] mb-1 block">Actor</label>
              <Select value={filters.actor} onChange={(e) => setFilters({ ...filters, actor: e.target.value })}>
                <option value="">Alle</option>
                {(facets.actors ?? []).map((a) => (
                  <option key={a} value={a}>
                    {a}
                  </option>
                ))}
              </Select>
            </div>
            <div>
              <label className="text-xs text-[#999] mb-1 block">Entity</label>
              <Select
                value={filters.entity_type}
                onChange={(e) => setFilters({ ...filters, entity_type: e.target.value })}
              >
                <option value="">Alle</option>
                {(facets.entity_types ?? []).map((t) => (
                  <option key={t} value={t}>
                    {t}
                  </option>
                ))}
              </Select>
            </div>
            <div>
              <label className="text-xs text-[#999] mb-1 block">Action</label>
              <Select value={filters.action} onChange={(e) => setFilters({ ...filters, action: e.target.value })}>
                <option value="">Alle</option>
                {(facets.actions ?? []).map((a) => (
                  <option key={a} value={a}>
                    {a}
                  </option>
                ))}
              </Select>
            </div>
            <div>
              <label className="text-xs text-[#999] mb-1 block">Van</label>
              <Input
                type="date"
                value={filters.from}
                onChange={(e) => setFilters({ ...filters, from: e.target.value })}
              />
            </div>
            <div>
              <label className="text-xs text-[#999] mb-1 block">Tot</label>
              <Input
                type="date"
                value={filters.to}
                onChange={(e) => setFilters({ ...filters, to: e.target.value })}
              />
            </div>
          </div>
        </Card>

        <Card>
          <Table>
            <THead>
              <TR className="hover:bg-transparent">
                <TH className="w-8"></TH>
                <TH>Tijd</TH>
                <TH>Actor</TH>
                <TH>Action</TH>
                <TH>Entity</TH>
                <TH>ID</TH>
                <TH>IP</TH>
              </TR>
            </THead>
            <TBody>
              {entries.map((e) => {
                const isOpen = expanded.has(e.id);
                return (
                  <Fragment key={e.id}>
                    <TR onClick={() => toggle(e.id)} className="cursor-pointer">
                      <TD>
                        {isOpen ? (
                          <ChevronDown className="h-4 w-4 text-[#666]" />
                        ) : (
                          <ChevronRight className="h-4 w-4 text-[#666]" />
                        )}
                      </TD>
                      <TD className="text-xs text-[#999] font-mono">
                        {new Date(e.created_at).toLocaleString('nl-NL')}
                      </TD>
                      <TD className="text-xs">{e.actor_email ?? '—'}</TD>
                      <TD>
                        <Badge variant={ACTION_VARIANTS[e.action] ?? 'muted'}>{e.action}</Badge>
                      </TD>
                      <TD className="text-xs">{e.entity_type}</TD>
                      <TD className="font-mono text-xs text-[#999]">{e.entity_id ?? '—'}</TD>
                      <TD className="font-mono text-xs text-[#666]">{e.ip ?? '—'}</TD>
                    </TR>
                    {isOpen && (
                      <TR className="hover:bg-transparent">
                        <TD colSpan={7} className="bg-[#0A0A0A]">
                          <div className="grid grid-cols-2 gap-4 p-4">
                            <div>
                              <h4 className="text-xs text-[#999] mb-2">Before</h4>
                              <pre className="text-xs font-mono text-[#999] bg-[#141414] border border-[#333] rounded p-3 overflow-x-auto max-h-60">
                                {e.before_state ? JSON.stringify(e.before_state, null, 2) : '—'}
                              </pre>
                            </div>
                            <div>
                              <h4 className="text-xs text-[#999] mb-2">After</h4>
                              <pre className="text-xs font-mono text-[#999] bg-[#141414] border border-[#333] rounded p-3 overflow-x-auto max-h-60">
                                {e.after_state ? JSON.stringify(e.after_state, null, 2) : '—'}
                              </pre>
                            </div>
                            {e.metadata && (
                              <div className="col-span-2">
                                <h4 className="text-xs text-[#999] mb-2">Metadata</h4>
                                <pre className="text-xs font-mono text-[#999] bg-[#141414] border border-[#333] rounded p-3 overflow-x-auto">
                                  {JSON.stringify(e.metadata, null, 2)}
                                </pre>
                              </div>
                            )}
                          </div>
                        </TD>
                      </TR>
                    )}
                  </Fragment>
                );
              })}
            </TBody>
          </Table>
          {entries.length === 0 && (
            <div className="p-10 text-center text-sm text-[#666]">Geen audit-entries voor deze filters.</div>
          )}
        </Card>
      </PageBody>
    </AppShell>
  );
}
