import React, { useState, useEffect, useMemo } from 'react';
import {
  Clock, Funnel, MagnifyingGlass, ArrowClockwise, User,
  PencilSimple, Trash, Plus, Shield, CurrencyDollar,
  CalendarBlank, ArrowUp, ArrowDown, FileText
} from '@phosphor-icons/react';
import axios from 'axios';
import toast from 'react-hot-toast';

const BRAND = '#5D4037';

const Glass = ({ children, className = '' }) => (
  <div className={`rounded-2xl border border-white border-opacity-40 shadow-lg ${className}`}
       style={{ background:'rgba(255,255,255,0.88)', backdropFilter:'blur(14px)', WebkitBackdropFilter:'blur(14px)' }}>
    {children}
  </div>
);

const eventStyle = {
  created:  { bg:'#dcfce7', text:'#15803d', icon: Plus },
  updated:  { bg:'#fef9c3', text:'#a16207', icon: PencilSimple },
  deleted:  { bg:'#fee2e2', text:'#dc2626', icon: Trash },
  assigned: { bg:'#e0e7ff', text:'#4338ca', icon: Shield },
  revoked:  { bg:'#ffe4e6', text:'#be123c', icon: ArrowDown },
  login:    { bg:'#EFEBE9', text:'#4E342E', icon: User },
  default:  { bg:'#f3f4f6', text:'#374151', icon: FileText },
};

const inferEvent = (log) => {
  if (log.event) return log.event;
  const d = (log.description || '').toLowerCase();
  if (d.includes('logged in') || d.includes('login')) return 'login';
  if (d.includes('creat')) return 'created';
  if (d.includes('updat')) return 'updated';
  if (d.includes('delet')) return 'deleted';
  if (d.includes('assign')) return 'assigned';
  if (d.includes('revok')) return 'revoked';
  return 'default';
};

const entityColor = {
  Employee:           BRAND,
  User:               '#8b5cf6',
  Role:               '#f59e0b',
  Expense:            '#10b981',
  IntercompanyLoan:   '#ef4444',
  ProfitSweepRule:    '#06b6d4',
  Company:            '#ec4899',
};

export default function AuditLogs() {
  const [logs,    setLogs]    = useState([]);
  const [stats,   setStats]   = useState(null);
  const [loading, setLoading] = useState(true);
  const [search,  setSearch]  = useState('');
  const [filters, setFilters] = useState({ entityType:'', action:'', dateFrom:'', dateTo:'' });
  const [page,    setPage]    = useState(1);
  const PER_PAGE = 15;

  useEffect(() => { fetchLogs(); fetchStats(); }, []);

  const fetchLogs = async () => {
    try {
      setLoading(true);
      const params = {};
      if (filters.entityType) params.entity_type = filters.entityType;
      if (filters.action)     params.action       = filters.action;
      if (filters.dateFrom)   params.date_from    = filters.dateFrom;
      if (filters.dateTo)     params.date_to      = filters.dateTo;
      const res = await axios.get('/api/audit-logs', { params });
      setLogs(res.data?.data || res.data || []);
      setPage(1);
    } catch {
      toast.error('Failed to load audit logs');
    } finally {
      setLoading(false);
    }
  };

  const fetchStats = async () => {
    try {
      const res = await axios.get('/api/audit-logs/stats');
      setStats(res.data);
    } catch { /* silent */ }
  };

  const filtered = useMemo(() => {
    if (!search.trim()) return logs;
    const q = search.toLowerCase();
    return logs.filter(l =>
      l.description?.toLowerCase().includes(q) ||
      l.causer?.name?.toLowerCase().includes(q) ||
      l.subject_type?.toLowerCase().includes(q)
    );
  }, [logs, search]);

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

  const clearFilters = () => {
    setFilters({ entityType:'', action:'', dateFrom:'', dateTo:'' });
    setSearch('');
    fetchLogs();
  };

  const fmtDate = (d) => d ? new Date(d).toLocaleString('en-GB',{ day:'2-digit', month:'short', year:'numeric', hour:'2-digit', minute:'2-digit' }) : '—';
  const entityName = (type) => type?.split('\\')?.pop() || '—';

  return (
    <div className="min-h-screen p-6" style={{ background:'linear-gradient(135deg,#EFEBE9 0%,#e8e8fd 50%,#f8faff 100%)' }}>

      {/* ── Header ──────────────────────────────────────────── */}
      <div className="mb-6 flex flex-wrap items-center justify-between gap-4">
        <div>
          <h1 className="text-2xl font-black text-gray-900 flex items-center gap-2">
            <Clock size={28} weight="duotone" style={{ color: BRAND }} /> Audit Trail
          </h1>
          <p className="text-gray-500 text-sm mt-1">Full activity log — employees, roles, salaries, performance, leaves</p>
        </div>
        <button onClick={() => { fetchLogs(); fetchStats(); }}
          className="flex items-center gap-2 px-4 py-2 text-white rounded-xl text-sm font-semibold shadow-md transition-all hover:shadow-lg"
          style={{ background: BRAND }}>
          <ArrowClockwise size={16} weight="bold" /> Refresh
        </button>
      </div>

      {/* ── Stats Cards ─────────────────────────────────────── */}
      <div className="grid grid-cols-2 md:grid-cols-4 gap-4 mb-6">
        {[
          { label:'Total Events',  value: stats?.total       || logs.length, icon: FileText,        color: BRAND    },
          { label:'Today',         value: stats?.today       || 0,           icon: CalendarBlank,   color:'#10b981' },
          { label:'This Week',     value: stats?.this_week   || 0,           icon: ArrowUp,         color:'#f59e0b' },
          { label:'Sensitive',     value: stats?.sensitive   || logs.filter(l=>l.event==='deleted').length, icon: Shield, color:'#ef4444' },
        ].map((s, i) => (
          <Glass key={i} className="p-4 flex items-center gap-3">
            <div className="w-10 h-10 rounded-xl flex items-center justify-center flex-shrink-0" style={{ background: s.color+'18' }}>
              <s.icon size={20} weight="duotone" style={{ color: s.color }} />
            </div>
            <div>
              <p className="text-xl font-black text-gray-900">{s.value}</p>
              <p className="text-xs text-gray-400">{s.label}</p>
            </div>
          </Glass>
        ))}
      </div>

      {/* ── Filters ─────────────────────────────────────────── */}
      <Glass className="p-4 mb-5">
        <div className="flex flex-wrap items-end gap-3">
          {/* Search */}
          <div className="flex-1 min-w-[220px]">
            <label className="block text-xs font-semibold text-gray-400 uppercase tracking-wider mb-1">Search</label>
            <div className="relative">
              <MagnifyingGlass size={15} className="absolute left-3 top-1/2 -translate-y-1/2 text-gray-400" />
              <input value={search} onChange={e => setSearch(e.target.value)} placeholder="Search logs…"
                className="w-full pl-9 pr-3 py-2 border border-gray-200 rounded-xl text-sm bg-white focus:ring-2 focus:border-transparent"
                style={{ '--tw-ring-color': BRAND }} />
            </div>
          </div>
          {/* Entity Type */}
          <div className="min-w-[160px]">
            <label className="block text-xs font-semibold text-gray-400 uppercase tracking-wider mb-1">Entity Type</label>
            <select value={filters.entityType} onChange={e => setFilters(p=>({...p,entityType:e.target.value}))}
              className="w-full px-3 py-2 border border-gray-200 rounded-xl text-sm bg-white focus:ring-2 focus:border-transparent"
              style={{ '--tw-ring-color': BRAND }}>
              <option value="">All Entities</option>
              <option value="Employee">Employee</option>
              <option value="User">User</option>
              <option value="Role">Role</option>
              <option value="Expense">Expense</option>
              <option value="IntercompanyLoan">Loan</option>
              <option value="ProfitSweepRule">Profit Sweep</option>
              <option value="Company">Company</option>
            </select>
          </div>
          {/* Action */}
          <div className="min-w-[140px]">
            <label className="block text-xs font-semibold text-gray-400 uppercase tracking-wider mb-1">Action</label>
            <select value={filters.action} onChange={e => setFilters(p=>({...p,action:e.target.value}))}
              className="w-full px-3 py-2 border border-gray-200 rounded-xl text-sm bg-white focus:ring-2 focus:border-transparent"
              style={{ '--tw-ring-color': BRAND }}>
              <option value="">All Actions</option>
              <option value="created">Created</option>
              <option value="updated">Updated</option>
              <option value="deleted">Deleted</option>
              <option value="assigned">Assigned</option>
              <option value="revoked">Revoked</option>
              <option value="logged in">Login</option>
            </select>
          </div>
          {/* Date Range */}
          <div className="min-w-[140px]">
            <label className="block text-xs font-semibold text-gray-400 uppercase tracking-wider mb-1">From</label>
            <input type="date" value={filters.dateFrom} onChange={e => setFilters(p=>({...p,dateFrom:e.target.value}))}
              className="w-full px-3 py-2 border border-gray-200 rounded-xl text-sm bg-white" />
          </div>
          <div className="min-w-[140px]">
            <label className="block text-xs font-semibold text-gray-400 uppercase tracking-wider mb-1">To</label>
            <input type="date" value={filters.dateTo} onChange={e => setFilters(p=>({...p,dateTo:e.target.value}))}
              className="w-full px-3 py-2 border border-gray-200 rounded-xl text-sm bg-white" />
          </div>
          <div className="flex gap-2">
            <button onClick={fetchLogs}
              className="flex items-center gap-2 px-4 py-2 text-white rounded-xl text-sm font-semibold transition-all"
              style={{ background: BRAND }}>
              <Funnel size={15} /> Apply
            </button>
            <button onClick={clearFilters}
              className="flex items-center gap-2 px-4 py-2 bg-gray-100 text-gray-600 rounded-xl text-sm font-medium hover:bg-gray-200 transition-all">
              <ArrowClockwise size={15} /> Clear
            </button>
          </div>
        </div>
      </Glass>

      {/* ── Log Table ───────────────────────────────────────── */}
      <Glass className="overflow-hidden">
        {loading ? (
          <div className="flex items-center justify-center py-16">
            <div className="w-12 h-12 rounded-full border-4 border-t-transparent animate-spin"
                 style={{ borderColor:`${BRAND}33`, borderTopColor: BRAND }} />
          </div>
        ) : (
          <>
            <div className="overflow-x-auto">
              <table className="w-full text-sm">
                <thead>
                  <tr style={{ background:`${BRAND}08`, borderBottom:`2px solid ${BRAND}18` }}>
                    <th className="px-4 py-3 text-left text-xs font-bold text-gray-500 uppercase tracking-wider">Timestamp</th>
                    <th className="px-4 py-3 text-left text-xs font-bold text-gray-500 uppercase tracking-wider">User</th>
                    <th className="px-4 py-3 text-left text-xs font-bold text-gray-500 uppercase tracking-wider">Action</th>
                    <th className="px-4 py-3 text-left text-xs font-bold text-gray-500 uppercase tracking-wider">Entity</th>
                    <th className="px-4 py-3 text-left text-xs font-bold text-gray-500 uppercase tracking-wider">Description</th>
                    <th className="px-4 py-3 text-left text-xs font-bold text-gray-500 uppercase tracking-wider">IP</th>
                  </tr>
                </thead>
                <tbody className="divide-y divide-gray-100">
                  {paginated.length === 0 && (
                    <tr>
                      <td colSpan={6} className="px-4 py-12 text-center">
                        <Clock size={36} className="mx-auto mb-2 text-gray-300" weight="duotone" />
                        <p className="text-gray-400 font-medium">No audit events found</p>
                        <p className="text-gray-300 text-xs mt-1">Try adjusting your filters</p>
                      </td>
                    </tr>
                  )}
                  {paginated.map((log, idx) => {
                    const ev = eventStyle[inferEvent(log)] || eventStyle.default;
                    const Ico = ev.icon;
                    const model = entityName(log.subject_type);
                    const entColor = entityColor[model] || '#6b7280';
                    return (
                      <tr key={idx} className="hover:bg-primary-50 hover:bg-opacity-40 transition-colors">
                        <td className="px-4 py-3 whitespace-nowrap text-xs text-gray-400 font-medium">
                          {fmtDate(log.created_at)}
                        </td>
                        <td className="px-4 py-3">
                          <div className="flex items-center gap-2">
                            <div className="w-6 h-6 rounded-full flex items-center justify-center text-white text-xs font-bold flex-shrink-0"
                                 style={{ background: BRAND }}>
                              {(log.causer?.name || 'S').charAt(0).toUpperCase()}
                            </div>
                            <div>
                              <span className="font-semibold text-gray-800 text-xs block">
                                {log.causer?.name || log.causer?.email || 'System'}
                              </span>
                              {log.causer?.email && log.causer?.name && <span className="text-gray-400 text-xs">{log.causer.email}</span>}
                            </div>
                          </div>
                        </td>
                        <td className="px-4 py-3">
                          <span className="inline-flex items-center gap-1 px-2 py-1 rounded-lg text-xs font-bold"
                                style={{ background: ev.bg, color: ev.text }}>
                            <Ico size={11} weight="bold" /> {inferEvent(log)}
                          </span>
                        </td>
                        <td className="px-4 py-3">
                          <span className="inline-flex items-center gap-1 px-2 py-1 rounded-lg text-xs font-semibold"
                                style={{ background: entColor+'15', color: entColor }}>
                            {model}{log.subject_id ? ` #${log.subject_id}` : ''}
                          </span>
                        </td>
                        <td className="px-4 py-3 text-gray-600 max-w-sm">
                          <p className="truncate text-xs">{log.description}</p>
                        </td>
                        <td className="px-4 py-3 text-xs">
                          {log.ip_address ? (
                            <span title={log.user_agent || ''} className="font-mono text-primary-600 cursor-help border-b border-dashed border-primary-300">
                              {log.ip_address}
                            </span>
                          ) : '—'}
                        </td>
                      </tr>
                    );
                  })}
                </tbody>
              </table>
            </div>

            {/* Pagination */}
            {totalPages > 1 && (
              <div className="px-4 py-3 border-t border-gray-100 flex items-center justify-between">
                <p className="text-xs text-gray-400">
                  Showing {Math.min((page-1)*PER_PAGE+1, filtered.length)}–{Math.min(page*PER_PAGE, filtered.length)} of {filtered.length}
                </p>
                <div className="flex gap-2">
                  <button onClick={() => setPage(p=>Math.max(1,p-1))} disabled={page===1}
                    className="px-3 py-1 rounded-lg text-xs font-semibold disabled:opacity-40 bg-gray-100 text-gray-600 hover:bg-gray-200 transition-all">← Prev</button>
                  {Array.from({length: Math.min(totalPages,5)}, (_,i) => i+1).map(n => (
                    <button key={n} onClick={() => setPage(n)}
                      className="px-3 py-1 rounded-lg text-xs font-semibold transition-all"
                      style={{ background: page===n ? BRAND : '#f3f4f6', color: page===n ? '#fff' : '#374151' }}>
                      {n}
                    </button>
                  ))}
                  <button onClick={() => setPage(p=>Math.min(totalPages,p+1))} disabled={page===totalPages}
                    className="px-3 py-1 rounded-lg text-xs font-semibold disabled:opacity-40 bg-gray-100 text-gray-600 hover:bg-gray-200 transition-all">Next →</button>
                </div>
              </div>
            )}
          </>
        )}
      </Glass>
    </div>
  );
}
