/**
 * Admin Logs Table
 * Enterprise Logging System — Admin Dashboard
 *
 * Renders paginated admin action logs with actor, affected user, action,
 * category, and a detail modal showing old/new values.
 */

'use client';

import { useState } from 'react';
import type { AdminLog } from '@/types/logging.types';
import { LogPagination } from './LogPagination';
import { LogDetailModal } from './LogDetailModal';

export function AdminLogsTable({
  logs,
  page,
  totalPages,
  total,
  limit,
  onPageChange,
}: {
  logs: AdminLog[];
  page: number;
  totalPages: number;
  total: number;
  limit: number;
  onPageChange: (page: number) => void;
}) {
  const [selected, setSelected] = useState<AdminLog | null>(null);

  return (
    <div className="overflow-hidden rounded-xl border border-white/5">
      <div className="overflow-x-auto">
        <table className="w-full min-w-[1000px] text-left text-sm">
          <thead className="border-b border-white/5 bg-slate-900/70 text-xs uppercase text-slate-400">
            <tr>
              <th className="px-4 py-3">Admin</th>
              <th className="px-4 py-3">Action</th>
              <th className="px-4 py-3">Category</th>
              <th className="px-4 py-3">Affected User</th>
              <th className="px-4 py-3">Resource</th>
              <th className="px-4 py-3">IP Address</th>
              <th className="px-4 py-3">Timestamp</th>
              <th className="px-4 py-3 text-right">Action</th>
            </tr>
          </thead>
          <tbody className="divide-y divide-white/5">
            {logs.length === 0 && (
              <tr>
                <td colSpan={8} className="px-4 py-10 text-center text-slate-500">
                  No admin logs found.
                </td>
              </tr>
            )}
            {logs.map((log) => (
              <tr key={log.id} className="hover:bg-white/[0.02]">
                <td className="px-4 py-3">
                  <div className="text-slate-200">{log.actorUser?.email ?? log.actorUserId?.slice(0, 12) ?? '—'}</div>
                </td>
                <td className="px-4 py-3 font-medium text-slate-200">{log.action.replace(/_/g, ' ')}</td>
                <td className="px-4 py-3 text-slate-400">{log.category.replace(/_/g, ' ')}</td>
                <td className="px-4 py-3 text-slate-400">{log.affectedUserId?.slice(0, 12) ?? '—'}</td>
                <td className="px-4 py-3 text-slate-400">
                  {log.resource ?? '—'}
                  {log.resourceId ? ` (${log.resourceId.slice(0, 8)}…)` : ''}
                </td>
                <td className="px-4 py-3 text-slate-400">{log.ipAddress ?? '—'}</td>
                <td className="px-4 py-3 text-slate-400">{new Date(log.createdAt).toLocaleString()}</td>
                <td className="px-4 py-3 text-right">
                  <button
                    onClick={() => setSelected(log)}
                    className="rounded-lg border border-white/10 px-2.5 py-1 text-xs text-slate-300 hover:bg-white/5"
                  >
                    View
                  </button>
                </td>
              </tr>
            ))}
          </tbody>
        </table>
      </div>

      <LogPagination page={page} totalPages={totalPages} total={total} limit={limit} onChange={onPageChange} />

      <LogDetailModal
        open={selected !== null}
        onClose={() => setSelected(null)}
        title="Admin Log Details"
        rows={
          selected
            ? [
                { label: 'ID', value: selected.id },
                { label: 'Admin', value: selected.actorUser?.email ?? selected.actorUserId ?? '—' },
                { label: 'Action', value: selected.action },
                { label: 'Category', value: selected.category },
                { label: 'Affected User', value: selected.affectedUserId ?? '—' },
                { label: 'Resource', value: `${selected.resource ?? ''} ${selected.resourceId ?? ''}`.trim() || '—' },
                { label: 'Details', value: selected.details ?? '—' },
                { label: 'Old Value', value: selected.oldValue ? JSON.stringify(selected.oldValue) : '—' },
                { label: 'New Value', value: selected.newValue ? JSON.stringify(selected.newValue) : '—' },
                { label: 'IP Address', value: selected.ipAddress ?? '—' },
                { label: 'Timestamp', value: new Date(selected.createdAt).toLocaleString() },
              ]
            : []
        }
        raw={selected?.metadata ?? undefined}
      />
    </div>
  );
}

