'use client';
import { useState, useMemo } from 'react';
import { useAuditLog, AuditEntry, AuditAction, AuditModule } from '../../lib/auditLog';

const ACTION_COLORS: Record<AuditAction, string> = {
  Create: 'bg-green-100 text-green-700',
  Read: 'bg-blue-100 text-blue-700',
  Update: 'bg-amber-100 text-amber-700',
  Delete: 'bg-red-100 text-red-700',
  Login: 'bg-teal-100 text-teal-700',
  Logout: 'bg-gray-100 text-gray-600',
  Export: 'bg-purple-100 text-purple-700',
  Import: 'bg-indigo-100 text-indigo-700',
  Approve: 'bg-emerald-100 text-emerald-700',
  Reject: 'bg-rose-100 text-rose-700',
};

const SEVERITY_COLORS: Record<string, string> = {
  low: 'bg-gray-100 text-gray-500',
  medium: 'bg-amber-100 text-amber-700',
  high: 'bg-red-100 text-red-700',
};

export default function AuditLogTab() {
  const { entries } = useAuditLog();
  const [search, setSearch] = useState('');
  const [filterModule, setFilterModule] = useState('All');
  const [filterAction, setFilterAction] = useState('All');
  const [filterSeverity, setFilterSeverity] = useState('All');
  const [expanded, setExpanded] = useState<string | null>(null);
  const [page, setPage] = useState(1);
  const PER_PAGE = 10;

  const modules = ['All', ...Array.from(new Set(entries.map(e => e.module)))];
  const actions = ['All', ...Array.from(new Set(entries.map(e => e.action)))];

  const filtered = useMemo(() => entries.filter(e => {
    const q = search.toLowerCase();
    const matchSearch = !q || e.user.toLowerCase().includes(q) || e.description.toLowerCase().includes(q) || e.recordId.toLowerCase().includes(q);
    const matchModule = filterModule === 'All' || e.module === filterModule;
    const matchAction = filterAction === 'All' || e.action === filterAction;
    const matchSeverity = filterSeverity === 'All' || e.severity === filterSeverity.toLowerCase();
    return matchSearch && matchModule && matchAction && matchSeverity;
  }), [entries, search, filterModule, filterAction, filterSeverity]);

  const paged = filtered.slice((page - 1) * PER_PAGE, page * PER_PAGE);
  const totalPages = Math.ceil(filtered.length / PER_PAGE);

  const exportCSV = () => {
    const headers = ['ID', 'Timestamp', 'User', 'Role', 'Module', 'Action', 'Record ID', 'Description', 'IP Address', 'Severity'];
    const rows = filtered.map(e => [e.id, e.timestamp, e.user, e.role, e.module, e.action, e.recordId, `"${e.description}"`, e.ipAddress, e.severity]);
    const csv = [headers, ...rows].map(r => r.join(',')).join('\n');
    const blob = new Blob([csv], { type: 'text/csv' });
    const url = URL.createObjectURL(blob);
    const a = document.createElement('a');
    a.href = url;
    a.download = `audit_log_${new Date().toISOString().split('T')[0]}.csv`;
    a.click();
    URL.revokeObjectURL(url);
  };

  return (
    <div className="space-y-5">
      <div className="bg-white rounded-2xl shadow-sm border border-gray-100 p-5">
        <div className="flex items-center justify-between mb-4">
          <div>
            <h3 className="font-bold text-gray-800">System Audit Log</h3>
            <p className="text-xs text-gray-500 mt-0.5">{filtered.length} records • Retained for 7 years per compliance policy</p>
          </div>
          <button onClick={exportCSV} className="flex items-center gap-2 px-4 py-2.5 rounded-xl text-white text-sm font-semibold cursor-pointer whitespace-nowrap" style={{ background: '#b828a0' }}>
            <div className="w-4 h-4 flex items-center justify-center"><i className="ri-download-2-line text-sm"></i></div>
            Export CSV
          </button>
        </div>

        <div className="grid grid-cols-4 gap-3 mb-4">
          <input
            type="text"
            placeholder="Search user, action, record..."
            value={search}
            onChange={e => { setSearch(e.target.value); setPage(1); }}
            className="col-span-1 border border-gray-200 rounded-xl px-3 py-2 text-sm outline-none"
          />
          {[
            { label: 'Module', value: filterModule, options: modules, setter: setFilterModule },
            { label: 'Action', value: filterAction, options: actions, setter: setFilterAction },
            { label: 'Severity', value: filterSeverity, options: ['All', 'Low', 'Medium', 'High'], setter: setFilterSeverity },
          ].map(f => (
            <div key={f.label} className="relative">
              <div className="flex items-center border border-gray-200 rounded-xl px-3 py-2 bg-white cursor-pointer"
                onClick={() => {}}>
                <span className="text-sm text-gray-600 flex-1">{f.value}</span>
                <div className="w-4 h-4 flex items-center justify-center">
                  <i className="ri-arrow-down-s-line text-gray-400 text-sm"></i>
                </div>
              </div>
              <select
                value={f.value}
                onChange={e => { f.setter(e.target.value); setPage(1); }}
                className="absolute inset-0 opacity-0 cursor-pointer w-full pr-8"
              >
                {f.options.map(o => <option key={o}>{o}</option>)}
              </select>
            </div>
          ))}
        </div>

        <div className="grid grid-cols-4 gap-3 mb-5">
          {[
            { label: 'Total Entries', value: entries.length, color: 'text-gray-800', bg: 'bg-gray-50' },
            { label: 'High Severity', value: entries.filter(e => e.severity === 'high').length, color: 'text-red-700', bg: 'bg-red-50' },
            { label: 'Today', value: entries.filter(e => e.timestamp.startsWith('2026-04-14')).length, color: 'text-blue-700', bg: 'bg-blue-50' },
            { label: 'This Week', value: entries.filter(e => e.timestamp >= '2026-04-08').length, color: 'text-purple-700', bg: 'bg-purple-50' },
          ].map(s => (
            <div key={s.label} className={`${s.bg} rounded-xl p-3`}>
              <p className="text-xs text-gray-500 mb-1">{s.label}</p>
              <p className={`text-2xl font-bold ${s.color}`}>{s.value}</p>
            </div>
          ))}
        </div>

        <div className="overflow-x-auto">
          <table className="w-full">
            <thead>
              <tr className="border-b border-gray-100">
                {['Timestamp', 'User / Role', 'Module', 'Action', 'Record', 'Description', 'Severity', ''].map(h => (
                  <th key={h} className="text-left py-2.5 px-3 text-xs font-semibold text-gray-500">{h}</th>
                ))}
              </tr>
            </thead>
            <tbody>
              {paged.map(entry => (
                <>
                  <tr key={entry.id} className="border-b border-gray-50 hover:bg-gray-50/50 transition-colors">
                    <td className="py-3 px-3 text-xs text-gray-500 whitespace-nowrap">{entry.timestamp}</td>
                    <td className="py-3 px-3">
                      <p className="text-sm font-medium text-gray-700">{entry.user}</p>
                      <p className="text-xs text-gray-400">{entry.role}</p>
                    </td>
                    <td className="py-3 px-3 text-xs text-gray-600">{entry.module}</td>
                    <td className="py-3 px-3">
                      <span className={`px-2 py-0.5 rounded-full text-xs font-semibold ${ACTION_COLORS[entry.action]}`}>{entry.action}</span>
                    </td>
                    <td className="py-3 px-3 text-xs font-mono text-gray-600">{entry.recordId}</td>
                    <td className="py-3 px-3 text-xs text-gray-600 max-w-56 truncate">{entry.description}</td>
                    <td className="py-3 px-3">
                      <span className={`px-2 py-0.5 rounded-full text-xs font-medium capitalize ${SEVERITY_COLORS[entry.severity]}`}>{entry.severity}</span>
                    </td>
                    <td className="py-3 px-3">
                      {(entry.oldValue || entry.newValue) && (
                        <button onClick={() => setExpanded(expanded === entry.id ? null : entry.id)}
                          className="text-xs text-pink-600 hover:underline cursor-pointer whitespace-nowrap">
                          {expanded === entry.id ? 'Hide' : 'Details'}
                        </button>
                      )}
                    </td>
                  </tr>
                  {expanded === entry.id && (
                    <tr key={`${entry.id}-exp`} className="bg-pink-50/30">
                      <td colSpan={8} className="px-3 py-3">
                        <div className="grid grid-cols-2 gap-4">
                          {entry.oldValue && (
                            <div>
                              <p className="text-xs font-semibold text-gray-500 mb-1">Old Value</p>
                              <pre className="text-xs text-red-700 bg-red-50 rounded-lg p-2 overflow-x-auto">{JSON.stringify(JSON.parse(entry.oldValue), null, 2)}</pre>
                            </div>
                          )}
                          {entry.newValue && (
                            <div>
                              <p className="text-xs font-semibold text-gray-500 mb-1">New Value</p>
                              <pre className="text-xs text-green-700 bg-green-50 rounded-lg p-2 overflow-x-auto">{JSON.stringify(JSON.parse(entry.newValue), null, 2)}</pre>
                            </div>
                          )}
                        </div>
                        <p className="text-xs text-gray-400 mt-2">IP: {entry.ipAddress} • Entry ID: {entry.id}</p>
                      </td>
                    </tr>
                  )}
                </>
              ))}
            </tbody>
          </table>
        </div>

        {totalPages > 1 && (
          <div className="flex items-center justify-between mt-4">
            <p className="text-xs text-gray-500">Showing {(page - 1) * PER_PAGE + 1}–{Math.min(page * PER_PAGE, filtered.length)} of {filtered.length}</p>
            <div className="flex items-center gap-1">
              <button onClick={() => setPage(p => Math.max(1, p - 1))} disabled={page === 1}
                className="w-8 h-8 flex items-center justify-center rounded-lg border border-gray-200 text-gray-600 disabled:opacity-40 cursor-pointer hover:bg-gray-50">
                <i className="ri-arrow-left-s-line text-base"></i>
              </button>
              {Array.from({ length: Math.min(totalPages, 5) }, (_, i) => i + 1).map(p => (
                <button key={p} onClick={() => setPage(p)}
                  className={`w-8 h-8 flex items-center justify-center rounded-lg text-xs font-medium cursor-pointer ${page === p ? 'text-white' : 'border border-gray-200 text-gray-600 hover:bg-gray-50'}`}
                  style={page === p ? { background: '#b828a0' } : {}}>
                  {p}
                </button>
              ))}
              <button onClick={() => setPage(p => Math.min(totalPages, p + 1))} disabled={page === totalPages}
                className="w-8 h-8 flex items-center justify-center rounded-lg border border-gray-200 text-gray-600 disabled:opacity-40 cursor-pointer hover:bg-gray-50">
                <i className="ri-arrow-right-s-line text-base"></i>
              </button>
            </div>
          </div>
        )}
      </div>
    </div>
  );
}
