'use client'

import { useState } from 'react'

import { useI18n } from '@/components/providers/i18n-provider'
import { DataTable, type Column } from '@/components/ui/data-table'
import { Dialog } from '@/components/ui/controls'
import { Badge, KeyValue } from '@/components/ui/display'

export interface AuditRow {
  id: string
  ts: number
  userEmail: string
  userRole: string
  action: string
  entity: string
  entityId: string | null
  ip: string | null
  status: string
  detail: string | null
  beforeJson: string | null
  afterJson: string | null
}

/**
 * The audit log (§35).
 *
 * Before/after payloads are stored as JSON strings and shown verbatim in the detail
 * dialogue. Rendering them raw rather than prettifying them into prose is intentional:
 * an audit record is evidence, and evidence should not be paraphrased.
 */
export function AuditTable({ rows, actions }: { rows: AuditRow[]; actions: string[] }) {
  const { t, n, dateTime } = useI18n()
  const [detail, setDetail] = useState<AuditRow | null>(null)

  const columns: Array<Column<AuditRow>> = [
    {
      key: 'ts',
      header: t('audit.columns.time'),
      sortValue: (row) => row.ts,
      cell: (row) => <span className="tnum text-[11px] text-text-muted">{dateTime(row.ts)}</span>,
    },
    {
      key: 'user',
      header: t('audit.columns.user'),
      sortValue: (row) => row.userEmail,
      cell: (row) => <span className="font-mono text-[11px] text-text">{row.userEmail}</span>,
    },
    {
      key: 'role',
      header: t('audit.columns.role'),
      secondary: true,
      sortValue: (row) => row.userRole,
      cell: (row) => (
        <span className="text-[11px] text-text-muted">
          {row.userRole === 'anonymous' ? row.userRole : t(`role.${row.userRole}`)}
        </span>
      ),
    },
    {
      key: 'action',
      header: t('audit.columns.action'),
      sortValue: (row) => row.action,
      cell: (row) => <Badge tone="muted">{row.action}</Badge>,
    },
    {
      key: 'entity',
      header: t('audit.columns.entity'),
      secondary: true,
      sortValue: (row) => row.entity,
      cell: (row) => <span className="font-mono text-[11px] text-text-muted">{row.entity}</span>,
    },
    {
      key: 'ip',
      header: t('audit.columns.ip'),
      secondary: true,
      sortValue: (row) => row.ip ?? '',
      cell: (row) => (
        <span className="font-mono text-[11px] text-text-faint">{row.ip ?? t('common.na')}</span>
      ),
    },
    {
      key: 'status',
      header: t('audit.columns.status'),
      align: 'end',
      sortValue: (row) => row.status,
      cell: (row) => (
        <Badge
          tone={row.status === 'success' ? 'brand' : 'neutral'}
          className={row.status === 'denied' ? 'border-critical/40 bg-critical/12 text-critical' : undefined}
        >
          {row.status}
        </Badge>
      ),
    },
  ]

  return (
    <>
      <DataTable
        rows={rows}
        columns={columns}
        getRowKey={(row) => row.id}
        searchable={(row) => `${row.userEmail} ${row.action} ${row.entity} ${row.detail ?? ''}`}
        initialSort={{ key: 'ts', direction: 'desc' }}
        onRowClick={setDetail}
        caption={t('audit.title')}
        emptyTitle={t('audit.empty')}
        pageSize={30}
        dense
        filters={[
          {
            key: 'action',
            label: t('audit.columns.action'),
            options: actions.map((action) => ({ value: action, label: action })),
            match: (row, value) => row.action === value,
          },
          {
            key: 'status',
            label: t('audit.columns.status'),
            options: [
              { value: 'success', label: 'success' },
              { value: 'denied', label: 'denied' },
              { value: 'error', label: 'error' },
            ],
            match: (row, value) => row.status === value,
          },
        ]}
      />

      <Dialog
        open={detail !== null}
        onClose={() => setDetail(null)}
        title={detail?.action ?? ''}
        description={detail ? dateTime(detail.ts) : undefined}
        closeLabel={t('common.close')}
      >
        {detail ? (
          <div className="space-y-4">
            <dl className="divide-y divide-border/60">
              <KeyValue label={t('audit.columns.user')} value={detail.userEmail} mono />
              <KeyValue
                label={t('audit.columns.role')}
                value={detail.userRole === 'anonymous' ? detail.userRole : t(`role.${detail.userRole}`)}
              />
              <KeyValue label={t('audit.columns.entity')} value={detail.entity} mono />
              {detail.entityId ? (
                <KeyValue label="ID" value={detail.entityId} mono />
              ) : null}
              <KeyValue label={t('audit.columns.ip')} value={detail.ip ?? t('common.na')} mono />
              <KeyValue label={t('audit.columns.status')} value={detail.status} />
            </dl>

            {detail.detail ? (
              <p className="rounded-lg border border-border bg-surface-2/50 px-3 py-2.5 text-xs leading-relaxed text-text-muted">
                {detail.detail}
              </p>
            ) : null}

            {detail.beforeJson || detail.afterJson ? (
              <div className="grid gap-3 sm:grid-cols-2">
                <div>
                  <p className="mb-1.5 text-[10px] font-semibold uppercase tracking-wide text-text-faint">
                    {t('audit.before')}
                  </p>
                  <pre
                    dir="ltr"
                    className="overflow-x-auto rounded-lg border border-border bg-base px-3 py-2.5 font-mono text-[11px] text-text-muted"
                  >
                    {detail.beforeJson ?? t('common.na')}
                  </pre>
                </div>
                <div>
                  <p className="mb-1.5 text-[10px] font-semibold uppercase tracking-wide text-text-faint">
                    {t('audit.after')}
                  </p>
                  <pre
                    dir="ltr"
                    className="overflow-x-auto rounded-lg border border-border bg-base px-3 py-2.5 font-mono text-[11px] text-text-muted"
                  >
                    {detail.afterJson ?? t('common.na')}
                  </pre>
                </div>
              </div>
            ) : (
              <p className="text-xs text-text-faint">{t('audit.noChange')}</p>
            )}

            <p className="text-[11px] text-text-faint">
              {t('common.timestamp')}: {n(detail.ts)}
            </p>
          </div>
        ) : null}
      </Dialog>
    </>
  )
}
