'use client';

import React, { useState, useEffect } from 'react';
import AdminSidebar from '@/components/admin/AdminSidebar';
import {
  FileText,
  Search,
  Filter,
  ShieldCheck,
  RefreshCw,
  Eye,
  X,
  Code,
} from 'lucide-react';

export default function AdminAuditLogsPage() {
  const [logs, setLogs] = useState<any[]>([]);
  const [loading, setLoading] = useState(true);
  const [searchTerm, setSearchTerm] = useState('');
  const [selectedLog, setSelectedLog] = useState<any>(null);

  const fetchAuditLogs = async () => {
    try {
      const res = await fetch('/api/v1/admin/audit');
      const data = await res.json();
      if (data.success) {
        setLogs(data.data || []);
      }
    } catch {}
    finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    fetchAuditLogs();
  }, []);

  const filteredLogs = logs.filter((log) => {
    const q = searchTerm.toLowerCase();
    return (
      log.action.toLowerCase().includes(q) ||
      log.actorEmail.toLowerCase().includes(q) ||
      log.resource.toLowerCase().includes(q)
    );
  });

  return (
    <div className="flex min-h-screen bg-[#070b14] text-slate-100">
      <AdminSidebar />

      <div className="flex-1 flex flex-col min-w-0">
        <header className="h-16 border-b border-slate-800 bg-[#070b14]/80 backdrop-blur-md px-6 flex items-center justify-between sticky top-0 z-30">
          <div className="flex items-center gap-2">
            <span className="w-2 h-2 rounded-full bg-amber-400"></span>
            <span className="text-xs font-bold text-amber-300 font-mono">Platform Security Audit Log</span>
          </div>
          <button
            onClick={fetchAuditLogs}
            className="px-3 py-1.5 bg-slate-900 hover:bg-slate-800 border border-slate-700 text-slate-300 text-xs font-semibold rounded-xl flex items-center gap-1.5 transition-colors"
          >
            <RefreshCw className="w-3.5 h-3.5" />
            Refresh
          </button>
        </header>

        <main className="flex-1 p-6 space-y-6 overflow-y-auto max-w-7xl">
          <div className="flex flex-wrap items-center justify-between gap-4">
            <div>
              <h1 className="text-xl font-bold text-white flex items-center gap-2">
                <FileText className="w-5 h-5 text-amber-400" />
                Security & Administrative Audit Trail
              </h1>
              <p className="text-xs text-slate-400 mt-0.5">
                Immutable event trail of administrative modifications, key creations, role elevations, and logins.
              </p>
            </div>

            <div className="flex items-center gap-2 min-w-[280px]">
              <Search className="w-4 h-4 text-slate-400" />
              <input
                type="text"
                value={searchTerm}
                onChange={(e) => setSearchTerm(e.target.value)}
                placeholder="Search by action, actor, resource..."
                className="w-full bg-slate-900 border border-slate-700 rounded-xl px-3.5 py-1.5 text-xs text-white placeholder:text-slate-500 focus:outline-none focus:border-amber-500 font-mono"
              />
            </div>
          </div>

          <div className="glass-panel rounded-2xl p-6 border border-slate-800 space-y-4">
            <div className="overflow-x-auto">
              <table className="w-full text-left text-xs font-mono">
                <thead>
                  <tr className="border-b border-slate-800 text-slate-400 text-[11px]">
                    <th className="py-3 px-3">Timestamp</th>
                    <th className="py-3 px-3">Actor Email</th>
                    <th className="py-3 px-3">Action</th>
                    <th className="py-3 px-3">Resource</th>
                    <th className="py-3 px-3">Details</th>
                    <th className="py-3 px-3 text-right">Inspect</th>
                  </tr>
                </thead>
                <tbody className="divide-y divide-slate-800/60 text-slate-300">
                  {filteredLogs.length > 0 ? (
                    filteredLogs.map((log) => (
                      <tr key={log.id} className="hover:bg-slate-900/40 transition-colors">
                        <td className="py-3 px-3 text-slate-400">
                          {new Date(log.createdAt).toLocaleString()}
                        </td>
                        <td className="py-3 px-3 font-semibold text-white">{log.actorEmail}</td>
                        <td className="py-3 px-3">
                          <span className="px-2 py-0.5 rounded bg-amber-500/20 text-amber-300 font-bold text-[10px]">
                            {log.action}
                          </span>
                        </td>
                        <td className="py-3 px-3 text-emerald-400">{log.resource}</td>
                        <td className="py-3 px-3 text-slate-400 max-w-xs truncate font-sans">
                          {log.details || 'N/A'}
                        </td>
                        <td className="py-3 px-3 text-right">
                          <button
                            onClick={() => setSelectedLog(log)}
                            className="px-2.5 py-1 bg-slate-800 hover:bg-slate-700 text-slate-200 text-[11px] rounded-lg transition-colors inline-flex items-center gap-1 font-sans"
                          >
                            <Eye className="w-3 h-3" />
                            View
                          </button>
                        </td>
                      </tr>
                    ))
                  ) : (
                    <tr>
                      <td colSpan={6} className="py-6 text-center text-slate-500 font-sans">
                        {loading ? 'Loading audit logs...' : 'No audit records found.'}
                      </td>
                    </tr>
                  )}
                </tbody>
              </table>
            </div>
          </div>

          {/* Audit Log Modal */}
          {selectedLog && (
            <div className="fixed inset-0 bg-black/75 backdrop-blur-sm z-50 flex items-center justify-center p-4">
              <div className="glass-panel w-full max-w-lg rounded-2xl p-6 border border-slate-700 space-y-4 shadow-2xl animate-in fade-in zoom-in-95 duration-200">
                <div className="flex items-center justify-between border-b border-slate-800 pb-3">
                  <div className="flex items-center gap-2">
                    <Code className="w-5 h-5 text-amber-400" />
                    <h3 className="text-base font-bold text-white">Audit Event Details</h3>
                  </div>
                  <button onClick={() => setSelectedLog(null)} className="text-slate-400 hover:text-white p-1">
                    <X className="w-4 h-4" />
                  </button>
                </div>

                <div className="space-y-2 text-xs">
                  <div className="flex justify-between py-1 border-b border-slate-800 font-mono">
                    <span className="text-slate-400">Action:</span>
                    <span className="text-amber-400 font-bold">{selectedLog.action}</span>
                  </div>
                  <div className="flex justify-between py-1 border-b border-slate-800 font-mono">
                    <span className="text-slate-400">Actor:</span>
                    <span className="text-white">{selectedLog.actorEmail}</span>
                  </div>
                  <div className="flex justify-between py-1 border-b border-slate-800 font-mono">
                    <span className="text-slate-400">Resource:</span>
                    <span className="text-emerald-400">{selectedLog.resource}</span>
                  </div>
                </div>

                <div className="space-y-1.5">
                  <span className="text-xs font-bold text-slate-300">Raw Event JSON</span>
                  <pre className="p-3 rounded-xl bg-slate-950 border border-slate-800 text-[11px] font-mono text-slate-200 overflow-x-auto max-h-52">
                    {selectedLog.details ? JSON.stringify(JSON.parse(selectedLog.details), null, 2) : '{}'}
                  </pre>
                </div>
              </div>
            </div>
          )}
        </main>
      </div>
    </div>
  );
}
