'use client';
import { useEffect, useState, useCallback } from 'react';
import { adminService } from '@/services/admin.service';
import type { AuditLogEntry, AdminLogEntry, PaginationMeta } from '@/types/admin.types';

export default function AdminLogsPage() {
  const [auditLogs, setAuditLogs] = useState<AuditLogEntry[]>([]);
  const [adminLogs, setAdminLogs] = useState<AdminLogEntry[]>([]);
  const [meta, setMeta] = useState<PaginationMeta | null>(null);
  const [loading, setLoading] = useState(true);
  const [tab, setTab] = useState<'audit' | 'admin'>('audit');
  const [actionFilter, setActionFilter] = useState('');
  const [resourceFilter, setResourceFilter] = useState('');
  const [page, setPage] = useState(1);

  const fetchLogs = useCallback(async () => {
    setLoading(true);
    try {
      const params: any = { page, limit: 25 };
      if (actionFilter) params.action = actionFilter;
      if (resourceFilter) params.resource = resourceFilter;
      if (tab === 'audit') {
        const res = await adminService.getAuditLogs(params);
        setAuditLogs(res.data); setMeta(res.meta);
      } else {
        const res = await adminService.getAdminLogs(params);
        setAdminLogs(res.data); setMeta(res.meta);
      }
    } catch (e) { console.error(e); }
    finally { setLoading(false); }
  }, [page, actionFilter, resourceFilter, tab]);

  useEffect(() => { fetchLogs(); }, [fetchLogs]);

  const logs = tab === 'audit' ? auditLogs : adminLogs;

  return (
    <div className="space-y-6">
      <div className="flex flex-col gap-4 sm:flex-row sm:items-center sm:justify-between">
        <div>
          <h1 className="text-2xl font-bold text-white">System Logs</h1>
          <p className="mt-1 text-sm text-white/50">Audit trail and admin action logs</p>
        </div>
      </div>

      <div className="flex gap-4 border-b border-white/10">
        {(['audit', 'admin'] as const).map((t) => (
          <button key={t} onClick={() => { setTab(t); setPage(1); }} className={`pb-2 text-sm font-medium capitalize ${tab === t ? 'text-white border-b-2 border-indigo-400' : 'text-slate-500 hover:text-slate-300'}`}>
            {t === 'audit' ? 'Audit Logs' : 'Admin Logs'}
          </button>
        ))}
      </div>

      <div className="flex flex-wrap gap-3">
        <input type="text" placeholder="Filter by action..." value={actionFilter} onChange={(e) => { setActionFilter(e.target.value); setPage(1); }} className="rounded-lg border border-white/10 bg-white/5 px-3 py-2 text-xs text-white placeholder-slate-500 focus:border-indigo-500 focus:outline-none w-48" />
        <input type="text" placeholder="Filter by resource..." value={resourceFilter} onChange={(e) => { setResourceFilter(e.target.value); setPage(1); }} className="rounded-lg border border-white/10 bg-white/5 px-3 py-2 text-xs text-white placeholder-slate-500 focus:border-indigo-500 focus:outline-none w-48" />
        <button onClick={fetchLogs} className="rounded-lg bg-white/10 px-3 py-2 text-xs text-white/70 hover:bg-white/20">Refresh</button>
      </div>

      <div className="overflow-x-auto rounded-xl border border-white/5">
        <table className="w-full text-left text-xs">
          <thead className="border-b border-white/5 bg-white/[0.02]">
            <tr>
              <th className="px-4 py-3 text-slate-400">Date</th>
              <th className="px-4 py-3 text-slate-400">Action</th>
              <th className="px-4 py-3 text-slate-400">Resource</th>
              <th className="px-4 py-3 text-slate-400">Actor</th>
              <th className="px-4 py-3 text-slate-400">Details</th>
              <th className="px-4 py-3 text-slate-400">IP</th>
            </tr>
          </thead>
          <tbody>
            {loading ? <tr><td colSpan={6} className="px-4 py-8 text-center text-slate-500">Loading...</td></tr>
            : logs.length === 0 ? <tr><td colSpan={6} className="px-4 py-8 text-center text-slate-500">No logs found</td></tr>
            : logs.map((log: any) => (
              <tr key={log.id} className="border-b border-white/5 hover:bg-white/[0.02]">
                <td className="px-4 py-3 text-slate-300 whitespace-nowrap">{new Date(log.createdAt).toLocaleString()}</td>
                <td className="px-4 py-3 font-mono text-white">{log.action}</td>
                <td className="px-4 py-3 text-slate-300">{log.resource || '-'}{log.resourceId ? ` #${log.resourceId.slice(0, 8)}` : ''}</td>
                <td className="px-4 py-3 text-slate-300">
                  {tab === 'admin' ? `${log.actorUser?.firstName || ''} ${log.actorUser?.lastName || ''}`.trim() || log.actorUser?.email || '-' : log.email || '-'}
                </td>
                <td className="px-4 py-3 text-slate-400 max-w-[200px] truncate">{log.details || '-'}</td>
                <td className="px-4 py-3 text-slate-400 font-mono">{log.ipAddress || '-'}</td>
              </tr>
            ))}
          </tbody>
        </table>
      </div>

      {meta && (
        <div className="flex items-center justify-between">
          <p className="text-xs text-slate-500">Page {meta.page} of {meta.totalPages} ({meta.total} entries)</p>
          <div className="flex gap-2">
            <button disabled={page <= 1} onClick={() => setPage(page - 1)} className="rounded-lg bg-white/5 px-3 py-1.5 text-xs text-white disabled:opacity-30 hover:bg-white/10">Previous</button>
            <button disabled={page >= meta.totalPages} onClick={() => setPage(page + 1)} className="rounded-lg bg-white/5 px-3 py-1.5 text-xs text-white disabled:opacity-30 hover:bg-white/10">Next</button>
          </div>
        </div>
      )}
    </div>
  );
}
