/**
 * Error Logs Table
 * Enterprise Logging System — Admin Dashboard
 *
 * Renders paginated error logs with severity badges, route, status code,
 * and a detail modal showing the sanitized stack trace.
 */

'use client';

import { useState } from 'react';
import type { ErrorLog } from '@/types/logging.types';
import { LogPagination } from './LogPagination';
import { LogDetailModal } from './LogDetailModal';

function SeverityBadge({ severity }: { severity: string }) {
  const colors: Record<string, string> = {
    CRITICAL: 'bg-red-500/20 text-red-300',
    ERROR: 'bg-rose-500/15 text-rose-400',
    HIGH: 'bg-orange-500/15 text-orange-400',
    MEDIUM: 'bg-amber-500/15 text-amber-400',
    LOW: 'bg-sky-500/15 text-sky-400',
    INFO: 'bg-emerald-500/15 text-emerald-400',
  };
  return (
    <span className={`rounded-full px-2 py-0.5 text-xs font-medium ${colors[severity] ?? 'bg-slate-500/15 text-slate-400'}`}>
      {severity}
    </span>
  );
}

export function ErrorLogsTable({
  logs,
  page,
  totalPages,
  total,
  limit,
  onPageChange,
}: {
  logs: ErrorLog[];
  page: number;
  totalPages: number;
  total: number;
  limit: number;
  onPageChange: (page: number) => void;
}) {
  const [selected, setSelected] = useState<ErrorLog | 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">Severity</th>
              <th className="px-4 py-3">Message</th>
              <th className="px-4 py-3">Method</th>
              <th className="px-4 py-3">Route</th>
              <th className="px-4 py-3">Status</th>
              <th className="px-4 py-3">Service</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 error logs found.
                </td>
              </tr>
            )}
            {logs.map((log) => (
              <tr key={log.id} className="hover:bg-white/[0.02]">
                <td className="px-4 py-3">
                  <SeverityBadge severity={log.severity} />
                </td>
                <td className="max-w-[300px] px-4 py-3">
                  <div className="truncate text-slate-200">{log.message}</div>
                </td>
                <td className="px-4 py-3 text-slate-400">{log.httpMethod ?? '—'}</td>
                <td className="max-w-[240px] px-4 py-3">
                  <div className="truncate text-slate-400">{log.route ?? '—'}</div>
                </td>
                <td className="px-4 py-3 text-slate-400">{log.statusCode ?? '—'}</td>
                <td className="px-4 py-3 text-slate-400">{log.service ?? '—'}</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="Error Log Details"
        rows={
          selected
            ? [
                { label: 'ID', value: selected.id },
                { label: 'Message', value: selected.message },
                { label: 'Error Name', value: selected.name ?? '—' },
                { label: 'Severity', value: selected.severity },
                { label: 'Method', value: selected.httpMethod ?? '—' },
                { label: 'Route', value: selected.route ?? '—' },
                { label: 'Status Code', value: selected.statusCode ?? '—' },
                { label: 'Service', value: selected.service ?? '—' },
                { label: 'Context', value: selected.context ?? '—' },
                { label: 'User ID', value: selected.userId ?? '—' },
                { label: 'Sanitized', value: selected.sanitized ? 'Yes (secrets redacted)' : 'No' },
                { label: 'Stack Trace', value: selected.stackTrace ?? '—' },
                { label: 'Timestamp', value: new Date(selected.createdAt).toLocaleString() },
              ]
            : []
        }
        raw={selected?.metadata ?? undefined}
      />
    </div>
  );
}

