import type { AuditListItem } from '@/audit/types';
import { formatAuditLocal } from '@/audit/formatAuditTime';
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from '@/components/ui/table';
import { auditActionLabel } from '@/applicant/audit/actionLabels';
import { Button } from '@/components/ui/button';

interface AuditLogTableProps {
  items: AuditListItem[];
  onSelect: (row: AuditListItem) => void;
  page: number;
  total: number;
  pageSize: number;
  loading: boolean;
  onPrev: () => void;
  onNext: () => void;
}

export function AuditLogTable({
  items,
  onSelect,
  page,
  total,
  pageSize,
  loading,
  onPrev,
  onNext,
}: AuditLogTableProps) {
  const start = total === 0 ? 0 : (page - 1) * pageSize + 1;
  const end = Math.min(page * pageSize, total);

  return (
    <div className="space-y-3">
      <div className="rounded-md border">
        <Table>
          <TableHeader>
            <TableRow>
              <TableHead className="w-[168px]">Thời gian</TableHead>
              <TableHead>Tài khoản</TableHead>
              <TableHead className="w-[100px]">Hành động</TableHead>
              <TableHead>Đơn sáng kiến</TableHead>
              <TableHead className="hidden lg:table-cell w-[240px]">Tóm tắt meta</TableHead>
            </TableRow>
          </TableHeader>
          <TableBody>
            {loading && (
              <TableRow>
                <TableCell colSpan={5} className="text-center text-muted-foreground">
                  Đang tải…
                </TableCell>
              </TableRow>
            )}
            {!loading &&
              items.map((row) => {
                let metaBrief = '';
                try {
                  const m = row.metadata ?? {};
                  if (typeof m.path === 'string') metaBrief += m.path as string;
                  if (typeof m.caseId === 'string')
                    metaBrief += (metaBrief ? ' · ' : '') + (m.caseId as string);
                  if (typeof m.source === 'string')
                    metaBrief += (metaBrief ? ' · ' : '') + (m.source as string);
                  if (!metaBrief)
                    metaBrief = Object.keys(row.metadata || {}).length
                      ? JSON.stringify(row.metadata)
                      : '';
                } catch {
                  metaBrief = '';
                }
                return (
                  <TableRow
                    key={row.id}
                    className="cursor-pointer hover:bg-muted/60"
                    onClick={() => onSelect(row)}
                  >
                    <TableCell className="align-top whitespace-nowrap text-xs">
                      {formatAuditLocal(row.occurred_at)}
                    </TableCell>
                    <TableCell className="align-top text-sm">
                      <div className="font-medium truncate max-w-[200px]" title={row.actor_email}>
                        {row.actor_email}
                      </div>
                      <div className="text-xs text-muted-foreground truncate">{row.actor_role}</div>
                    </TableCell>
                    <TableCell className="align-top text-sm">{auditActionLabel(row.action)}</TableCell>
                    <TableCell className="align-top text-sm">
                      <div className="font-mono text-xs">{row.entity_type}</div>
                      {row.entity_id && (
                        <div className="text-xs text-muted-foreground truncate max-w-[320px]" title={row.entity_id}>
                          {row.entity_id}
                        </div>
                      )}
                      {(row.has_before || row.has_after) && (
                        <div className="text-[10px] text-muted-foreground mt-1">
                          {row.has_before ? 'before' : ''}{row.has_before && row.has_after ? ' · ' : ''}{row.has_after ? 'after' : ''}
                        </div>
                      )}
                    </TableCell>
                    <TableCell className="hidden lg:table-cell align-top text-xs font-mono break-all">
                      <span title={metaBrief}>{metaBrief.slice(0, 120)}{metaBrief.length > 120 ? '…' : ''}</span>
                    </TableCell>
                  </TableRow>
                );
              })}
            {!loading && items.length === 0 && (
              <TableRow>
                <TableCell colSpan={5} className="text-center text-muted-foreground">
                  Không có sự kiện trong khoảng thời gian đã chọn.
                </TableCell>
              </TableRow>
            )}
          </TableBody>
        </Table>
      </div>

      <div className="flex flex-wrap items-center justify-between gap-3 text-sm text-muted-foreground">
        <div>
          {total > 0 ? (
            <>
              Hiển thị {start}–{end} / {total}
            </>
          ) : (
            'Không có bản ghi'
          )}
        </div>
        <div className="flex gap-2">
          <Button type="button" variant="outline" size="sm" onClick={onPrev} disabled={page <= 1 || loading}>
            Trước
          </Button>
          <Button
            type="button"
            variant="outline"
            size="sm"
            onClick={onNext}
            disabled={loading || page * pageSize >= total}
          >
            Sau
          </Button>
        </div>
      </div>
    </div>
  );
}
