/**
 * Login Logs Table
 * Enterprise Logging System — Admin Dashboard
 *
 * Renders paginated login/authentication logs with status badges and
 * a detail view modal.
 */

'use client';

import { useState } from 'react';
import type { LoginLog } from '@/types/logging.types';
import { LogPagination } from './LogPagination';
import { LogDetailModal } from './LogDetailModal';

function StatusBadge({ status }: { status: string }) {
  const colors: Record<string, string> = {
    SUCCESS: 'bg-emerald-500/15 text-emerald-400',
    FAILED: 'bg-rose-500/15 text-rose-400',
    BLOCKED: 'bg-red-500/15 text-red-400',
    PENDING: 'bg-amber-500/15 text-amber-400',
    EXPIRED: 'bg-slate-500/15 text-slate-400',
  };
  return (
    <span className={`rounded-full px-2 py-0.5 text-xs font-medium ${colors[status] ?? 'bg-slate-500/15 text-slate-400'}`}>
      {status}
    </span>
  );
}

export function LoginLogsTable({
  logs,
  page,
  totalPages,
  total,
  limit,
  onPageChange,
}: {
  logs: LoginLog[];
  page: number;
  totalPages: number;
  total: number;
  limit: number;
  onPageChange: (page: number) => void;
}) {
  const [selected, setSelected] = useState<LoginLog | null>(null);

  return (
    <div className="overflow-hidden rounded-xl border border-white/5">
      <div className="overflow-x-auto">
        <table className="w-full min-w-[900px] 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">Event</th>
              <th className="px-4 py-3">User</th>
              <th className="px-4 py-3">Status</th>
              <th className="px-4 py-3">IP Address</th>
              <th className="px-4 py-3">Browser / OS</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={7} className="px-4 py-10 text-center text-slate-500">
                  No login logs found.
                </td>
              </tr>
            )}
            {logs.map((log) => (
              <tr key={log.id} className="hover:bg-white/[0.02]">
                <td className="px-4 py-3 font-medium text-slate-200">{log.event.replace(/_/g, ' ')}</td>
                <td className="px-4 py-3">
                  <div className="text-slate-200">{log.email ?? '—'}</div>
                  <div className="text-xs text-slate-500">{log.userId?.slice(0, 12) ?? ''}</div>
                </td>
                <td className="px-4 py-3">
                  <StatusBadge status={log.status} />
                </td>
                <td className="px-4 py-3 text-slate-400">{log.ipAddress ?? '—'}</td>
                <td className="px-4 py-3 text-slate-400">
                  {log.browser ?? 'unknown'}
                  {log.os ? ` · ${log.os}` : ''}
                </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="Login Log Details"
        rows={
          selected
            ? [
                { label: 'ID', value: selected.id },
                { label: 'Event', value: selected.event },
                { label: 'Status', value: selected.status },
                { label: 'User', value: selected.email ?? '—' },
                { label: 'User ID', value: selected.userId ?? '—' },
                { label: 'IP Address', value: selected.ipAddress ?? '—' },
                { label: 'Browser', value: selected.browser ?? '—' },
                { label: 'OS', value: selected.os ?? '—' },
                { label: 'Device', value: selected.device ?? '—' },
                { label: 'Failure Reason', value: selected.failureReason ?? '—' },
                { label: 'Location', value: selected.location ? JSON.stringify(selected.location) : '—' },
                { label: 'Timestamp', value: new Date(selected.createdAt).toLocaleString() },
              ]
            : []
        }
        raw={selected?.metadata ?? undefined}
      />
    </div>
  );
}

