'use client';

import { useCallback, useEffect, useState } from 'react';
import { useRouter } from 'next/navigation';
import { api } from '@/lib/api';
import { useAuth } from '@/components/auth-context';
import SearchableSelect from '@/components/SearchableSelect';
import BackToDashboard from '@/components/BackToDashboard';
import { PageLoader } from '@/components/DotLoader';
import { formatDateTime } from '@/lib/dates';

interface AuthEvent {
  id: number;
  user: number | null;
  user_email: string | null;
  event_type: string;
  ip_address: string | null;
  user_agent: string | null;
  device_fingerprint: string | null;
  created_at: string;
}

const EVENT_OPTIONS = [
  { value: 'ALL', label: 'All Events' },
  { value: 'LOGIN_SUCCESS', label: 'Login Success' },
  { value: 'LOGIN_FAIL', label: 'Login Failed' },
  { value: 'LOCKOUT', label: 'Account Lockout' },
  { value: 'MFA_FAIL', label: 'MFA Failed' },
  { value: 'LOGIN_ATTEMPT_MCP', label: 'MCP Login Attempt' },
  { value: 'LOGIN_SUCCESS_MCP', label: 'MCP Login Success' },
  { value: 'PASSWORD_CHANGE', label: 'Password Changed' },
];

const EVENT_BADGE: Record<string, string> = {
  LOGIN_SUCCESS: 'text-emerald-700 bg-emerald-50 border-emerald-200 dark:text-emerald-300 dark:bg-emerald-950/40 dark:border-emerald-900/40',
  LOGIN_SUCCESS_MCP: 'text-emerald-700 bg-emerald-50 border-emerald-200 dark:text-emerald-300 dark:bg-emerald-950/40 dark:border-emerald-900/40',
  PASSWORD_CHANGE: 'text-[#405189] bg-[#405189]/10 border-[#405189]/20',
  LOGIN_ATTEMPT_MCP: 'text-slate-600 bg-slate-100 border-slate-200 dark:text-slate-300 dark:bg-slate-800 dark:border-slate-700',
  LOGIN_FAIL: 'text-rose-700 bg-rose-50 border-rose-200 dark:text-rose-300 dark:bg-rose-950/40 dark:border-rose-900/40',
  MFA_FAIL: 'text-rose-700 bg-rose-50 border-rose-200 dark:text-rose-300 dark:bg-rose-950/40 dark:border-rose-900/40',
  LOCKOUT: 'text-amber-700 bg-amber-50 border-amber-200 dark:text-amber-300 dark:bg-amber-950/40 dark:border-amber-900/40',
};

const label = (v: string) => EVENT_OPTIONS.find((o) => o.value === v)?.label || v;

const maskEmail = (email: string | null | undefined) => {
  if (!email) return '—';
  const [local, domain] = email.split('@');
  if (!domain) return email;
  const visible = local.slice(0, 3);
  return `${visible}****@${domain}`;
};

export default function LoginHistoryPage() {
  const router = useRouter();
  const { user: me } = useAuth();
  const [loading, setLoading] = useState(true);
  const [rows, setRows] = useState<AuthEvent[]>([]);
  const [fetching, setFetching] = useState(false);

  // filters
  const [eventType, setEventType] = useState('ALL');
  const [q, setQ] = useState('');
  const [dateFrom, setDateFrom] = useState('');
  const [dateTo, setDateTo] = useState('');

  const load = useCallback(async () => {
    setFetching(true);
    try {
      const params = new URLSearchParams({ page_size: '500' });
      if (eventType !== 'ALL') params.set('event_type', eventType);
      if (q.trim()) params.set('q', q.trim());
      if (dateFrom) params.set('date_from', dateFrom);
      if (dateTo) params.set('date_to', dateTo);
      const res = (await api.get(`/audit-logs/?${params.toString()}`)) as any;
      const data = res?.data?.results ?? res?.data ?? res?.results ?? [];
      setRows(Array.isArray(data) ? data : []);
    } catch {
      setRows([]);
    } finally {
      setFetching(false);
    }
  }, [eventType, q, dateFrom, dateTo]);

  useEffect(() => {
    if (!me) return;
    (async () => {
      try {
        if (me.role !== 'ADMIN') { router.push('/dashboard'); return; }
        await load();
      } finally { setLoading(false); }
    })();
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [me, router]);

  const clearFilters = () => { setEventType('ALL'); setQ(''); setDateFrom(''); setDateTo(''); };
  const activeFilters = (eventType !== 'ALL' ? 1 : 0) + (q ? 1 : 0) + (dateFrom || dateTo ? 1 : 0);

  if (loading) return <PageLoader />;

  return (
        <main className="flex-1 p-6 overflow-x-auto">
          <BackToDashboard />
          <div className="bg-white dark:bg-slate-900 border border-slate-200 dark:border-slate-800 shadow-sm">
            {/* Filter bar */}
            <div className="p-4 border-b border-slate-200 dark:border-slate-800 grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-5 gap-3">
              <div className="lg:col-span-1">
                <label className="block text-[10px] uppercase font-bold text-slate-400 mb-1">Event Type</label>
                <SearchableSelect value={eventType} onChange={setEventType} isClearable={false} options={EVENT_OPTIONS} />
              </div>
              <div className="sm:col-span-2 lg:col-span-2">
                <label className="block text-[10px] uppercase font-bold text-slate-400 mb-1">Search</label>
                <input value={q} onChange={(e) => setQ(e.target.value)} onKeyDown={(e) => { if (e.key === 'Enter') load(); }}
                  placeholder="Email, name, IP, device, browser…"
                  className="w-full bg-white dark:bg-slate-900 border border-slate-200 dark:border-slate-800 px-3 py-2 text-xs focus:outline-none text-slate-800 dark:text-white" />
              </div>
              <div>
                <label className="block text-[10px] uppercase font-bold text-slate-400 mb-1">From</label>
                <input type="date" value={dateFrom} onChange={(e) => setDateFrom(e.target.value)}
                  className="w-full bg-white dark:bg-slate-900 border border-slate-200 dark:border-slate-800 px-3 py-2 text-xs focus:outline-none text-slate-800 dark:text-white" />
              </div>
              <div>
                <label className="block text-[10px] uppercase font-bold text-slate-400 mb-1">To</label>
                <input type="date" value={dateTo} onChange={(e) => setDateTo(e.target.value)}
                  className="w-full bg-white dark:bg-slate-900 border border-slate-200 dark:border-slate-800 px-3 py-2 text-xs focus:outline-none text-slate-800 dark:text-white" />
              </div>
              <div className="sm:col-span-2 lg:col-span-5 flex items-center gap-2">
                <button onClick={load} disabled={fetching}
                  className="bg-[#405189] hover:bg-[#364574] disabled:opacity-50 text-white px-5 py-2 text-xs font-bold cursor-pointer transition">
                  <i className="fa-solid fa-magnifying-glass mr-1.5"></i>{fetching ? 'Searching…' : 'Search'}
                </button>
                {activeFilters > 0 && (
                  <button onClick={() => { clearFilters(); }}
                    className="border border-slate-200 dark:border-slate-800 px-4 py-2 text-xs font-bold text-slate-600 dark:text-slate-300 hover:bg-slate-50 dark:hover:bg-slate-800 cursor-pointer transition">
                    Clear
                  </button>
                )}
                <span className="ml-auto text-xs font-semibold text-slate-400">{rows.length} event{rows.length === 1 ? '' : 's'}</span>
              </div>
            </div>

            {/* Table */}
            <div className="overflow-x-auto">
              <table className="w-full text-xs">
                <thead className="bg-slate-50 dark:bg-slate-950/40 text-slate-400 text-left text-[10px] uppercase">
                  <tr>
                    <th className="px-4 py-2.5 font-semibold w-12">S.No.</th>
                    <th className="px-4 py-2.5 font-semibold">User</th>
                    <th className="px-4 py-2.5 font-semibold">Event</th>
                    <th className="px-4 py-2.5 font-semibold">IP Address</th>
                    <th className="px-4 py-2.5 font-semibold">Device Fingerprint</th>
                    <th className="px-4 py-2.5 font-semibold">Browser / Device</th>
                    <th className="px-4 py-2.5 font-semibold whitespace-nowrap">Date &amp; Time</th>
                  </tr>
                </thead>
                <tbody>
                  {fetching ? (
                    <tr><td colSpan={7} className="px-4 py-10 text-center text-slate-400"><i className="fa-solid fa-spinner fa-spin mr-2"></i>Loading…</td></tr>
                  ) : rows.length === 0 ? (
                    <tr><td colSpan={7} className="px-4 py-10 text-center text-slate-400">No login events match your filters.</td></tr>
                  ) : rows.map((r, i) => (
                    <tr key={r.id} className="border-t border-slate-100 dark:border-slate-800 hover:bg-slate-50 dark:hover:bg-slate-800/40 align-top">
                      <td className="px-4 py-2.5 text-slate-400 font-semibold">{i + 1}</td>
                      <td className="px-4 py-2.5 font-semibold text-slate-700 dark:text-slate-200 whitespace-nowrap" title={r.user_email || ''}>{maskEmail(r.user_email)}</td>
                      <td className="px-4 py-2.5">
                        <span className={`inline-flex px-2 py-0.5 text-[10px] font-bold border ${EVENT_BADGE[r.event_type] || 'text-slate-600 bg-slate-100 border-slate-200'}`}>
                          {label(r.event_type)}
                        </span>
                      </td>
                      <td className="px-4 py-2.5 text-slate-600 dark:text-slate-300 whitespace-nowrap font-mono">{r.ip_address || '—'}</td>
                      <td className="px-4 py-2.5 text-slate-500 dark:text-slate-400 font-mono" title={r.device_fingerprint || ''}>
                        {r.device_fingerprint ? `${r.device_fingerprint.slice(0, 12)}…` : '—'}
                      </td>
                      <td className="px-4 py-2.5 text-slate-500 dark:text-slate-400 max-w-[240px] truncate" title={r.user_agent || ''}>{r.user_agent || '—'}</td>
                      <td className="px-4 py-2.5 text-slate-400 whitespace-nowrap">{formatDateTime(r.created_at)}</td>
                    </tr>
                  ))}
                </tbody>
              </table>
            </div>
          </div>
        </main>
  );
}
