'use client';
import { useState } from 'react';
import SectionHeader from './SectionHeader';

interface AuditEntry {
  id: number;
  user: string;
  userRole: string;
  action: string;
  module: string;
  entity: string;
  oldValue: string;
  newValue: string;
  timestamp: string;
  ipAddress: string;
}

const AUDIT_DATA: AuditEntry[] = [
  { id: 1, user: 'Jane Wambua', userRole: 'HR Admin', action: 'UPDATE', module: 'Organization Structure', entity: 'Department: ICT & Systems', oldValue: 'Parent: Executive', newValue: 'Parent: Executive', timestamp: '2026-04-14 09:22:14', ipAddress: '192.168.1.10' },
  { id: 2, user: 'Susan Kamau', userRole: 'HR Super Admin', action: 'CREATE', module: 'Grade Scale', entity: 'Grade Level 10 — Executive Director', oldValue: '—', newValue: 'Min: 300,000 / Mid: 375,000 / Max: 450,000', timestamp: '2026-04-14 08:55:30', ipAddress: '192.168.1.12' },
  { id: 3, user: 'Jane Wambua', userRole: 'HR Admin', action: 'DELETE', module: 'Policies', entity: 'Travel & Per Diem Policy v1.2', oldValue: 'Status: Active', newValue: 'Status: Archived', timestamp: '2026-04-13 16:44:01', ipAddress: '192.168.1.10' },
  { id: 4, user: 'Peter Kariuki', userRole: 'HR Super Admin', action: 'UPDATE', module: 'Numbering Rules', entity: 'Employee ID Format', oldValue: 'EMP-{year}-{seq}', newValue: 'EMP-{year}-{seq:4}', timestamp: '2026-04-13 14:30:22', ipAddress: '192.168.1.5' },
  { id: 5, user: 'Susan Kamau', userRole: 'HR Super Admin', action: 'CREATE', module: 'Calendar', entity: 'Blackout Period: Audit Period', oldValue: '—', newValue: '2026-06-15 to 2026-06-30', timestamp: '2026-04-13 11:15:55', ipAddress: '192.168.1.12' },
  { id: 6, user: 'John Mwangi', userRole: 'HR Admin', action: 'UPDATE', module: 'Vendors', entity: 'Jubilee Health Insurance', oldValue: 'Status: Active', newValue: 'Status: Expired', timestamp: '2026-04-12 17:02:44', ipAddress: '192.168.1.8' },
  { id: 7, user: 'Grace Muthoni', userRole: 'HR Super Admin', action: 'CREATE', module: 'Committees', entity: 'Promotions Committee', oldValue: '—', newValue: '5 members assigned', timestamp: '2026-04-12 14:28:19', ipAddress: '192.168.1.7' },
  { id: 8, user: 'Jane Wambua', userRole: 'HR Admin', action: 'UPDATE', module: 'Policies', entity: 'Code of Conduct v3.1 → v3.2', oldValue: 'Version: v3.1', newValue: 'Version: v3.2', timestamp: '2026-04-11 09:00:33', ipAddress: '192.168.1.10' },
  { id: 9, user: 'Peter Kariuki', userRole: 'HR Super Admin', action: 'DELETE', module: 'Organization Structure', entity: 'Department: Research & Innovation', oldValue: 'Headcount: 3', newValue: 'Deleted — staff reassigned', timestamp: '2026-04-10 16:45:12', ipAddress: '192.168.1.5' },
  { id: 10, user: 'Susan Kamau', userRole: 'HR Super Admin', action: 'UPDATE', module: 'Calendar', entity: 'Working Days Configuration', oldValue: 'Mon–Sat', newValue: 'Mon–Fri', timestamp: '2026-04-09 11:30:00', ipAddress: '192.168.1.12' },
  { id: 11, user: 'David Otieno', userRole: 'HR Admin', action: 'CREATE', module: 'Vendors', entity: 'Deloitte Training Institute', oldValue: '—', newValue: 'Service: Training Provider, Status: Pending', timestamp: '2026-04-08 13:22:40', ipAddress: '192.168.1.9' },
  { id: 12, user: 'Grace Muthoni', userRole: 'HR Super Admin', action: 'UPDATE', module: 'Report Templates', entity: 'Monthly Turnover Report', oldValue: 'Schedule: Quarterly', newValue: 'Schedule: Monthly', timestamp: '2026-04-07 10:10:05', ipAddress: '192.168.1.7' },
];

const actionColors: Record<string, string> = {
  CREATE: 'bg-green-100 text-green-700',
  UPDATE: 'bg-blue-100 text-blue-700',
  DELETE: 'bg-red-100 text-red-600',
};

const MODULE_FILTERS = ['All', 'Organization Structure', 'Grade Scale', 'Policies', 'Calendar', 'Numbering Rules', 'Vendors', 'Committees', 'Report Templates'];

export default function AuditLogPanel() {
  const [moduleFilter, setModuleFilter] = useState('All');
  const [actionFilter, setActionFilter] = useState('All');
  const [search, setSearch] = useState('');
  const [expanded, setExpanded] = useState<number | null>(null);

  const filtered = AUDIT_DATA.filter(e => {
    const matchMod = moduleFilter === 'All' || e.module === moduleFilter;
    const matchAct = actionFilter === 'All' || e.action === actionFilter;
    const matchSearch = !search || e.user.toLowerCase().includes(search.toLowerCase()) || e.entity.toLowerCase().includes(search.toLowerCase());
    return matchMod && matchAct && matchSearch;
  });

  return (
    <div>
      <SectionHeader icon="ri-history-line" title="Audit Log" desc="Track all configuration changes — who changed what, when and from where"
        action={<button className="flex items-center gap-2 px-4 py-2 rounded-xl border border-gray-200 text-xs font-medium text-gray-600 hover:bg-gray-50 cursor-pointer whitespace-nowrap">
          <div className="w-4 h-4 flex items-center justify-center"><i className="ri-download-2-line text-sm"></i></div> Export Log
        </button>} />

      <div className="bg-white rounded-2xl border border-gray-100 shadow-sm p-4 mb-4">
        <div className="flex items-center gap-3 mb-3">
          <div className="relative flex-1">
            <input value={search} onChange={e => setSearch(e.target.value)} placeholder="Search by user or entity..."
              className="w-full border border-gray-200 rounded-xl px-4 py-2.5 text-sm outline-none pl-9" />
            <div className="w-4 h-4 flex items-center justify-center absolute left-3 top-1/2 -translate-y-1/2"><i className="ri-search-line text-gray-400 text-sm"></i></div>
          </div>
          <div className="relative">
            <select value={actionFilter} onChange={e => setActionFilter(e.target.value)} className="border border-gray-200 rounded-xl px-3 py-2.5 text-xs outline-none appearance-none pr-7 cursor-pointer bg-white">
              <option>All</option>
              <option>CREATE</option>
              <option>UPDATE</option>
              <option>DELETE</option>
            </select>
            <div className="w-4 h-4 flex items-center justify-center absolute right-2 top-1/2 -translate-y-1/2 pointer-events-none"><i className="ri-arrow-down-s-line text-gray-400 text-xs"></i></div>
          </div>
        </div>
        <div className="flex gap-2 flex-wrap">
          {MODULE_FILTERS.map(m => (
            <button key={m} onClick={() => setModuleFilter(m)}
              className={`px-3 py-1 rounded-full text-xs font-medium cursor-pointer whitespace-nowrap border transition-all ${moduleFilter === m ? 'text-white border-transparent' : 'bg-gray-50 text-gray-500 border-gray-200'}`}
              style={moduleFilter === m ? { background: '#b828a0' } : {}}>{m}</button>
          ))}
        </div>
      </div>

      <div className="bg-white rounded-2xl border border-gray-100 shadow-sm overflow-hidden">
        <div className="px-5 py-3 border-b border-gray-100 flex items-center justify-between" style={{ background: '#fdf0fb' }}>
          <p className="text-xs font-semibold text-gray-600">{filtered.length} entries found</p>
          <p className="text-xs text-gray-400">All times in EAT (UTC+3)</p>
        </div>
        <div className="divide-y divide-gray-50">
          {filtered.map(entry => (
            <div key={entry.id} className="cursor-pointer hover:bg-pink-50/20 transition-colors" onClick={() => setExpanded(expanded === entry.id ? null : entry.id)}>
              <div className="flex items-center gap-4 px-5 py-3">
                <span className={`text-xs px-2.5 py-1 rounded-full font-bold flex-shrink-0 ${actionColors[entry.action]}`}>{entry.action}</span>
                <div className="flex-1 min-w-0">
                  <div className="flex items-center gap-2">
                    <p className="text-sm font-semibold text-gray-800 truncate">{entry.entity}</p>
                    <span className="text-xs px-2 py-0.5 rounded-full bg-gray-100 text-gray-500 flex-shrink-0">{entry.module}</span>
                  </div>
                  <p className="text-xs text-gray-500 mt-0.5">By <span className="font-semibold text-gray-700">{entry.user}</span> ({entry.userRole}) · {entry.timestamp}</p>
                </div>
                <div className="w-5 h-5 flex items-center justify-center flex-shrink-0">
                  <i className={`${expanded === entry.id ? 'ri-arrow-up-s-line' : 'ri-arrow-down-s-line'} text-gray-400 text-base`}></i>
                </div>
              </div>
              {expanded === entry.id && (
                <div className="px-5 pb-4 grid grid-cols-3 gap-4" style={{ background: '#fdf9ff' }}>
                  <div className="bg-white rounded-xl p-3 border border-gray-100">
                    <p className="text-xs text-gray-400 mb-1">Previous Value</p>
                    <p className="text-sm font-mono text-gray-700">{entry.oldValue}</p>
                  </div>
                  <div className="bg-white rounded-xl p-3 border border-gray-100">
                    <p className="text-xs text-gray-400 mb-1">New Value</p>
                    <p className="text-sm font-mono font-semibold text-gray-800">{entry.newValue}</p>
                  </div>
                  <div className="bg-white rounded-xl p-3 border border-gray-100">
                    <p className="text-xs text-gray-400 mb-1">IP Address</p>
                    <p className="text-sm font-mono text-gray-700">{entry.ipAddress}</p>
                  </div>
                </div>
              )}
            </div>
          ))}
          {filtered.length === 0 && (
            <div className="text-center py-10">
              <div className="w-10 h-10 flex items-center justify-center mx-auto mb-2"><i className="ri-search-2-line text-4xl text-gray-300"></i></div>
              <p className="text-sm text-gray-400">No audit entries match your filters</p>
            </div>
          )}
        </div>
      </div>
    </div>
  );
}
