import { useCatalogList } from '@/lib/useCatalog'
import { ListPageShell } from '@/components/ListPageShell'
import { DataTable } from '@/components/DataTable'
import { Pagination } from '@/components/Pagination'
import { SearchBar } from '@/components/SearchBar'

interface AuditRow {
  id: string; createdAt: string; superAdminUserId: string
  actionType: string; organizationId: string | null; organizationName: string | null
  entityType: string | null; entityId: string | null
  description: string | null; reason: string | null; ipAddress: string
}

export function SuperAdminAuditLogPage() {
  const list = useCatalogList<AuditRow>('/api/super-admin/audit-log')
  const exportCsv = () => {
    const rows = list.data?.items ?? []
    const header = 'Дата;Действие;Организация;Описание;Причина;IP\n'
    const csv = header + rows.map(r =>
      [r.createdAt, r.actionType, r.organizationName ?? '', r.description ?? '', r.reason ?? '', r.ipAddress]
        .map(s => `"${String(s).replace(/"/g, '""')}"`).join(';')
    ).join('\n')
    const blob = new Blob([csv], { type: 'text/csv;charset=utf-8' })
    const url = URL.createObjectURL(blob)
    const a = document.createElement('a')
    a.href = url; a.download = `audit-log-${new Date().toISOString().slice(0, 10)}.csv`
    a.click(); URL.revokeObjectURL(url)
  }
  return (
    <ListPageShell
      title="Журнал действий супер-админа"
      description="Все мутации SuperAdmin'а записываются автоматически с IP и причиной."
      actions={<>
        <SearchBar value={list.search} onChange={list.setSearch} />
        <button onClick={exportCsv} className="px-3 py-1.5 rounded-md text-sm border border-slate-300 dark:border-slate-600 hover:bg-slate-50 dark:hover:bg-slate-800">
          Экспорт CSV
        </button>
      </>}
      footer={list.data && list.data.total > 0 && (
        <Pagination page={list.page} pageSize={list.data.pageSize} total={list.data.total} onPageChange={list.setPage} />
      )}>
      <DataTable
        rows={list.data?.items ?? []}
        isLoading={list.isLoading}
        rowKey={(r) => r.id}
        columns={[
          { header: 'Дата', width: '160px', cell: (r) => new Date(r.createdAt).toLocaleString('ru') },
          { header: 'Действие', width: '140px', cell: (r) => <span className="font-mono text-xs">{r.actionType}</span> },
          { header: 'Организация', cell: (r) => r.organizationName ?? '—' },
          { header: 'Описание', cell: (r) => r.description ?? '—' },
          { header: 'Причина', cell: (r) => r.reason ?? '—' },
          { header: 'IP', width: '140px', cell: (r) => <span className="font-mono text-xs text-slate-500">{r.ipAddress}</span> },
        ]}
      />
    </ListPageShell>
  )
}
