/**
 * Request Logs Table
 * Enterprise Logging System — Admin Dashboard
 *
 * Renders paginated HTTP request/API logs with method, URL, status code,
 * duration, and a detail modal showing sanitized headers/query/body.
 */

'use client';

import { useState } from 'react';
import type { RequestLog } from '@/types/logging.types';
import { LogPagination } from './LogPagination';
import { LogDetailModal } from './LogDetailModal';

function MethodBadge({ method }: { method: string }) {
  const colors: Record<string, string> = {
    GET: 'bg-sky-500/15 text-sky-400',
    POST: 'bg-emerald-500/15 text-emerald-400',
    PUT: 'bg-amber-500/15 text-amber-400',
    PATCH: 'bg-violet-500/15 text-violet-400',
    DELETE: 'bg-rose-500/15 text-rose-400',
  };
  return (
    <span className={`rounded px-1.5 py-0.5 text-xs font-medium ${colors[method] ?? 'bg-slate-500/15 text-slate-400'}`}>
      {method}
    </span>
  );
}

function StatusBadge({ statusCode }: { statusCode: number }) {
  const color =
    statusCode < 300
      ? 'text-emerald-400'
      : statusCode < 400
        ? 'text-sky-400'
        : statusCode < 500
          ? 'text-amber-400'
          : 'text-rose-400';
  return <span className={`font-medium ${color}`}>{statusCode}</span>;
}

export function RequestLogsTable({
  logs,
  page,
  totalPages,
  total,
  limit,
  onPageChange,
}: {
  logs: RequestLog[];
  page: number;
  totalPages: number;
  total: number;
  limit: number;
  onPageChange: (page: number) => void;
}) {
  const [selected, setSelected] = useState<RequestLog | 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">Method</th>
              <th className="px-4 py-3">URL</th>
              <th className="px-4 py-3">Status</th>
              <th className="px-4 py-3">Duration</th>
              <th className="px-4 py-3">User</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 request logs found.
                </td>
              </tr>
            )}
            {logs.map((log) => (
              <tr key={log.id} className="hover:bg-white/[0.02]">
                <td className="px-4 py-3">
                  <MethodBadge method={log.method} />
                </td>
                <td className="max-w-[320px] px-4 py-3">
                  <div className="truncate text-slate-200">{log.url}</div>
                </td>
                <td className="px-4 py-3">
                  <StatusBadge statusCode={log.statusCode} />
                </td>
                <td className="px-4 py-3 text-slate-400">{log.durationMs}ms</td>
                <td className="px-4 py-3 text-slate-400">{log.userId?.slice(0, 12) ?? 'anonymous'}</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="Request Log Details"
        rows={
          selected
            ? [
                { label: 'ID', value: selected.id },
                { label: 'Request ID', value: selected.requestId ?? '—' },
                { label: 'Method', value: selected.method },
                { label: 'URL', value: selected.url },
                { label: 'Route', value: selected.route ?? '—' },
                { label: 'Status Code', value: selected.statusCode },
                { label: 'Duration', value: `${selected.durationMs}ms` },
                { label: 'Response Size', value: selected.responseSize ? `${selected.responseSize}B` : '—' },
                { label: 'User ID', value: selected.userId ?? '—' },
                { label: 'IP Address', value: selected.ipAddress ?? '—' },
                { label: 'Timestamp', value: new Date(selected.createdAt).toLocaleString() },
              ]
            : []
        }
        raw={
          selected
            ? {
                headers: selected.headers ?? undefined,
                query: selected.query ?? undefined,
                body: selected.body ?? undefined,
                userAgent: selected.userAgent ?? undefined,
              }
            : undefined
        }
      />
    </div>
  );
}

