'use client';

import { useState, useEffect } from 'react';
import { db, Item } from '@/lib/db';
import { inventoryApi } from '@/lib/api';
import PageShell from '@/components/PageShell';
import { History, X, Search, Filter, Activity, ArrowDownCircle, ArrowUpCircle, User, RefreshCw } from 'lucide-react';
import { cn } from '@/lib/utils';
import { fetchAndCacheItems } from '@/lib/sync';

export default function LogsPage() {
  const [auditLogs, setAuditLogs] = useState<any[]>([]);
  const [inventory, setInventory] = useState<Item[]>([]);
  const [loading, setLoading] = useState(true);
  const [searchQuery, setSearchQuery] = useState('');
  const [filterAction, setFilterAction] = useState('ALL');
  const [selectedLog, setSelectedLog] = useState<any | null>(null);

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

  const loadData = async () => {
    setLoading(true);
    try {
      // 1. First, try to get fresh items to resolve names
      let freshItems: Item[] = [];
      try {
        freshItems = await fetchAndCacheItems();
      } catch (itemErr) {
        console.warn("Item sync failed, using local cache for names", itemErr);
        freshItems = await db.items.toArray();
      }
      setInventory(freshItems);
      
      // 2. Then, fetch fresh logs
      const logs = await inventoryApi.getAuditLogs(100);
      
      // 3. Pre-resolve names to avoid UI flickering/mismatches
      const enrichedLogs = (logs || []).map((log: any) => {
        // [AUDIT HARDENING] Prioritize the historical snapshot from the backend
        if (log.target_item_name) {
          return { ...log, resolved_name: log.target_item_name };
        }

        // Fallback for legacy logs or system operations
        const hasTarget = log.target_item_id && String(log.target_item_id) !== 'null';
        const item = hasTarget ? freshItems.find(i => String(i.id) === String(log.target_item_id)) : null;
        
        return {
          ...log,
          resolved_name: item ? item.name : (hasTarget ? `Item #${log.target_item_id}` : "System Operation")
        };
      });

      setAuditLogs(enrichedLogs);
    } catch (err) {
      console.error("Critical log load failure:", err);
    } finally {
      setLoading(false);
    }
  };

  const filteredLogs = auditLogs.filter(log => {
    const matchesSearch = (log.resolved_name || '').toLowerCase().includes(searchQuery.toLowerCase()) ||
                         log.action.toLowerCase().includes(searchQuery.toLowerCase()) ||
                         (log.username || '').toLowerCase().includes(searchQuery.toLowerCase());
    
    const matchesAction = filterAction === 'ALL' || log.action.includes(filterAction);
    
    return matchesSearch && matchesAction;
  });

  // Calculate stats
  const totalCount = auditLogs.length;
  const inCount = auditLogs.filter(l => l.action.includes('IN')).length;
  const outCount = auditLogs.filter(l => l.action.includes('OUT') || l.action.includes('TRASH')).length;
  
  const mostActiveUser = auditLogs.length > 0 ? 
    Object.entries(auditLogs.reduce((acc: any, curr) => {
      const user = curr.username || 'System';
      acc[user] = (acc[user] || 0) + 1;
      return acc;
    }, {})).sort((a: any, b: any) => b[1] - a[1])[0]?.[0] : 'N/A';

  return (
    <PageShell>
      <main className="p-4 md:p-8 max-w-7xl mx-auto space-y-12">
        <header className="space-y-8">
          <div className="flex flex-col sm:flex-row sm:items-center justify-between gap-6">
            <div className="flex items-center gap-5">
              <div className="p-4 bg-primary/10 rounded-[2rem] text-primary border border-primary/20 shadow-xl shadow-primary/5">
                <History size={32} />
              </div>
              <div>
                <h1 className="text-3xl font-black tracking-tight text-white">Audit Dashboard</h1>
                <p className="text-xs text-slate-500 font-bold mt-1">Real-time Intervention Tracking</p>
              </div>
            </div>
            
            <div className="flex gap-2">
               <button 
                 onClick={loadData}
                 disabled={loading}
                 className="flex items-center gap-2 px-6 py-3 bg-slate-900 border border-slate-800 text-slate-400 hover:text-white rounded-2xl text-xs font-black transition-all active:scale-95 disabled:opacity-50"
               >
                 <RefreshCw size={14} className={cn(loading && "animate-spin")} />
                 Refresh Stream
               </button>
            </div>
          </div>

          {/* Stats Grid */}
          <div className="grid grid-cols-2 md:grid-cols-4 gap-4">
            <div className="bg-slate-900/80 border border-slate-700/40 p-2 px-4 rounded-xl flex items-center gap-4 shadow-lg backdrop-blur-sm">
              <Activity size={18} className="text-primary shrink-0 opacity-80" />
              <p className="text-sm font-bold text-slate-300 whitespace-nowrap">Total Events</p>
              <p className="text-xl font-black text-white tabular-nums ml-auto">{totalCount}</p>
            </div>
            <div className="bg-slate-900/80 border border-slate-700/40 p-2 px-4 rounded-xl flex items-center gap-4 shadow-lg backdrop-blur-sm">
              <ArrowDownCircle size={18} className="text-green-500 shrink-0 opacity-80" />
              <p className="text-sm font-bold text-slate-300 whitespace-nowrap">Check in</p>
              <p className="text-xl font-black text-green-500 tabular-nums ml-auto">{inCount}</p>
            </div>
            <div className="bg-slate-900/80 border border-slate-700/40 p-2 px-4 rounded-xl flex items-center gap-4 shadow-lg backdrop-blur-sm">
              <ArrowUpCircle size={18} className="text-rose-500 shrink-0 opacity-80" />
              <p className="text-sm font-bold text-slate-300 whitespace-nowrap">Check out</p>
              <p className="text-xl font-black text-rose-500 tabular-nums ml-auto">{outCount}</p>
            </div>
            <div className="bg-slate-900/80 border border-slate-700/40 p-2 px-4 rounded-xl flex items-center gap-4 shadow-lg backdrop-blur-sm overflow-hidden">
              <User size={18} className="text-indigo-400 shrink-0 opacity-80" />
              <p className="text-sm font-bold text-slate-300 whitespace-nowrap">Top Operator</p>
              <p className="text-base font-black text-amber-500 truncate ml-auto" title={mostActiveUser}>{mostActiveUser}</p>
            </div>
          </div>

          <div className="flex flex-col md:flex-row gap-4">
            <div className="relative group flex-1">
              <Search className="absolute left-5 top-1/2 -translate-y-1/2 text-slate-500 group-focus-within:text-primary transition-colors" size={20} />
              <input 
                type="text" 
                placeholder="Search logs by item name, user, or action details..." 
                value={searchQuery}
                onChange={(e) => setSearchQuery(e.target.value)}
                className="w-full bg-slate-950/50 border border-slate-900 focus:border-primary/50 rounded-3xl py-5 pl-14 pr-6 text-sm text-white placeholder:text-slate-700 outline-none transition-all shadow-2xl"
              />
            </div>
            
            <div className="flex items-center gap-1.5 p-1.5 bg-slate-900/50 border border-slate-900 rounded-[1.5rem] overflow-x-auto no-scrollbar">
              {[
                { label: 'All', value: 'ALL' },
                { label: 'Check in', value: 'CHECK_IN' },
                { label: 'Check out', value: 'CHECK_OUT' },
                { label: 'Trash', value: 'TRASH' },
                { label: 'Create', value: 'CREATE' },
                { label: 'System', value: 'DB' }
              ].map(action => (
                <button
                  key={action.value}
                  onClick={() => setFilterAction(action.value)}
                  className={cn(
                    "px-4 py-2.5 rounded-xl text-xs font-bold transition-all whitespace-nowrap",
                    filterAction === action.value 
                      ? "bg-primary text-white shadow-lg shadow-primary/20" 
                      : "text-slate-500 hover:text-slate-300 hover:bg-slate-800"
                  )}
                >
                  {action.label}
                </button>
              ))}
            </div>
          </div>
        </header>

        <section className="space-y-4">
          {loading ? (
            <div className="flex flex-col items-center justify-center py-32 text-slate-600 gap-4 animate-pulse">
               <div className="w-12 h-12 border-4 border-primary/20 border-t-primary rounded-full animate-spin" />
               <p className="text-[10px] font-black tracking-widest">Securing Audit Stream...</p>
            </div>
          ) : filteredLogs.length === 0 ? (
            <div className="bg-slate-900/20 border border-slate-800/50 border-dashed rounded-[3rem] py-24 flex flex-col items-center justify-center text-center gap-6">
               <div className="w-20 h-20 bg-slate-900 rounded-[2rem] flex items-center justify-center text-slate-700 border border-slate-800 shadow-inner">
                 <Search size={40} />
               </div>
               <div>
                 <p className="text-xl font-black text-slate-300">No interventions found</p>
                 <p className="text-xs text-slate-600 font-bold mt-2">Try adjusting your filters or search query</p>
               </div>
            </div>
          ) : (
            <div className="grid gap-4">
              {filteredLogs.map((log) => (
                <button
                  key={log.id}
                  onClick={() => setSelectedLog(log)}
                  className="w-full text-left bg-slate-900/30 border border-slate-800/20 p-2 px-4 rounded-xl flex items-center justify-between gap-4 hover:bg-slate-900/60 hover:border-slate-700/50 transition-all group active:scale-[0.99] relative overflow-hidden shadow-sm"
                >
                  <div className="flex-1 min-w-0 z-10 flex items-center gap-4">
                    {/* Compact Action Badge */}
                    <div className={cn(
                      "text-[9px] font-black px-2 py-0.5 rounded-md border min-w-[70px] text-center",
                      log.action.includes('CHECK_IN') ? "bg-green-500/5 text-green-500 border-green-500/20" : 
                      (log.action.includes('TRASH') ? "bg-rose-500/5 text-rose-500 border-rose-500/20" : 
                       (log.action.includes('DB') ? "bg-sky-500/5 text-sky-400 border-sky-500/20" :
                        (log.action.includes('DELETE') ? "bg-red-500/10 text-red-500 border-red-500/30" :
                         (log.action.includes('CREATE') ? "bg-indigo-500/5 text-indigo-400 border-indigo-500/20" : "bg-amber-500/5 text-amber-500 border-amber-500/20"))))
                    )}>
                      {log.action.replace('_', ' ')}
                    </div>
                    
                    <div className="flex-1 min-w-0">
                      <h3 className="text-sm font-bold text-white group-hover:text-primary transition-colors truncate">
                         {log.resolved_name}
                      </h3>
                      <div className="flex items-center gap-2 opacity-80">
                        <span className="text-[9px] font-black text-amber-500 tracking-tight">{log.username || 'System'}</span>
                        <span className="w-1 h-1 rounded-full bg-slate-700" />
                        <span className="text-[9px] text-slate-500 font-mono">
                          {new Date(log.timestamp).toLocaleDateString()} · {new Date(log.timestamp).toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' })}
                        </span>
                      </div>
                    </div>
                  </div>
                  
                  <div className="shrink-0 flex items-center gap-3 z-10">
                    <div className={cn(
                      "text-xl font-black tabular-nums min-w-[40px] text-right",
                      (log.quantity_change || 0) > 0 ? "text-green-500" : ((log.quantity_change || 0) < 0 ? "text-rose-500" : "text-indigo-400")
                    )}>
                      {log.quantity_change ? (log.quantity_change > 0 ? `+${log.quantity_change}` : log.quantity_change) : (log.action.includes('DB') ? 'SYS' : '±')}
                    </div>
                  </div>
                  
                  <div className="absolute inset-x-0 bottom-0 h-1 bg-gradient-to-r from-transparent via-primary/5 to-transparent opacity-0 group-hover:opacity-100 transition-opacity" />
                </button>
              ))}
            </div>
          )}
        </section>

        {/* Selected Log Modal */}
        {selectedLog && (
          <div className="fixed inset-0 z-[100] flex items-center justify-center p-4 bg-slate-950/80 backdrop-blur-xl animate-in fade-in duration-300">
            <div className="bg-slate-900 border border-slate-800 rounded-[3rem] p-10 max-w-lg w-full shadow-2xl space-y-8 animate-in zoom-in-95 duration-300">
              <div className="flex justify-between items-start">
                <div className="space-y-1">
                  <div className={cn(
                        "text-[10px] font-black px-4 py-1.5 rounded-full border inline-block",
                        selectedLog.action.includes('CHECK_IN') ? "bg-green-500/10 text-green-500 border-green-500/30" : 
                        (selectedLog.action.includes('TRASH') ? "bg-rose-500/10 text-rose-500 border-rose-500/30" : "bg-amber-500/10 text-amber-500 border-amber-500/30")
                      )}>
                    {selectedLog.action}
                  </div>
                  <h2 className="text-3xl font-black text-white tracking-tight leading-tight pt-2">
                    {selectedLog.resolved_name}
                  </h2>
                </div>
                <button onClick={() => setSelectedLog(null)} className="p-3 hover:bg-slate-800 rounded-2xl text-slate-500 transition-colors border border-slate-800">
                  <X size={24} />
                </button>
              </div>

              <div className="grid grid-cols-2 gap-6">
                <div className="space-y-1 bg-slate-950/50 p-4 rounded-2xl border border-slate-800">
                  <p className="text-[10px] font-black text-slate-600">Operator</p>
                  <p className="text-sm font-black text-white">{selectedLog.username || 'System Profile'}</p>
                </div>
                <div className="space-y-1 bg-slate-950/50 p-4 rounded-2xl border border-slate-800">
                  <p className="text-[10px] font-black text-slate-600">Delta</p>
                  <p className={cn(
                    "text-xl font-black",
                    (selectedLog.quantity_change || 0) > 0 ? "text-green-500" : "text-rose-500"
                  )}>
                    {selectedLog.quantity_change 
                      ? `${selectedLog.quantity_change > 0 ? '+' : ''}${selectedLog.quantity_change} Units` 
                      : (selectedLog.action.includes('DB') ? 'System' : 'No Delta')}
                  </p>
                </div>
              </div>

              <div className="space-y-4">
                <div className="space-y-1">
                  <p className="text-[10px] font-black text-slate-600">Timestamp</p>
                  <p className="text-sm font-bold text-slate-300 bg-slate-800/30 p-4 rounded-2xl border border-slate-800/50">
                    {new Date(selectedLog.timestamp).toLocaleString(undefined, { dateStyle: 'full', timeStyle: 'medium' })}
                  </p>
                </div>

                {selectedLog.target_snapshot && (() => {
                  try {
                    const snap = JSON.parse(selectedLog.target_snapshot);
                    return (
                      <div className="space-y-4">
                        <div className="flex items-center gap-2">
                           <div className="h-px flex-1 bg-slate-800" />
                           <p className="text-[10px] font-black text-slate-700 uppercase tracking-widest">Full Historical Context</p>
                           <div className="h-px flex-1 bg-slate-800" />
                        </div>
                        <div className="grid grid-cols-2 gap-3">
                          {Object.entries(snap).map(([key, val]) => (
                            val && key !== 'image_url' && (
                              <div key={key} className="bg-slate-950/30 p-3 rounded-xl border border-slate-800/40">
                                <p className="text-[8px] font-black text-slate-600 uppercase mb-1">{key.replace('_', ' ')}</p>
                                <p className="text-xs font-bold text-slate-300 truncate" title={String(val)}>{String(val)}</p>
                              </div>
                            )
                          ))}
                        </div>
                      </div>
                    );
                  } catch (e) { return null; }
                })()}

                {selectedLog.details && (
                  <div className="space-y-1">
                    <p className="text-[10px] font-black text-slate-600">Intervention Details</p>
                    <div className="bg-primary/5 text-primary/80 p-6 rounded-[2rem] border border-primary/10 text-sm font-bold leading-relaxed italic">
                      "{selectedLog.details}"
                    </div>
                  </div>
                )}

                {selectedLog.target_item_pn && (
                  <div className="space-y-1">
                    <p className="text-[10px] font-black text-slate-600">Historical Part Number</p>
                    <div className="bg-slate-800/20 text-slate-400 p-4 rounded-2xl border border-slate-800/50 text-xs font-mono">
                      {selectedLog.target_item_pn}
                    </div>
                  </div>
                )}
              </div>

              <button 
                onClick={() => setSelectedLog(null)}
                className="w-full bg-slate-800 hover:bg-slate-700 text-white font-black py-5 rounded-[2rem] transition-all active:scale-95 border border-slate-700"
              >
                Close Insights
              </button>
            </div>
          </div>
        )}
      </main>
    </PageShell>
  );
}
