import React, { useEffect, useState } from 'react';
import { 
  History, 
  Search, 
  Filter, 
  Eye, 
  User, 
  Activity, 
  Calendar,
  ShieldCheck,
  AlertTriangle,
  Info,
  ChevronRight,
  Database,
  X
} from 'lucide-react';
import { useAuditStore, AuditLog } from '../../store/audit';
import { Modal, ModalBody } from '../../components/ui/Modal';

const AuditLogs: React.FC = () => {
  const { logs, total, isLoading, fetchLogs } = useAuditStore();
  const [selectedLog, setSelectedLog] = useState<AuditLog | null>(null);
  const [filters, setFilters] = useState({
    user_email: '',
    action: '',
    entity_type: '',
    limit: 50,
    offset: 0
  });

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

  const getActionColor = (action: string) => {
    if (action.includes('FAILED') || action.includes('DELETE') || action.includes('DEACTIVATE')) {
      return 'bg-rose-500/10 text-rose-500 border-rose-500/20';
    }
    if (action.includes('SUCCESS') || action.includes('CREATE') || action.includes('ACTIVATE') || action.includes('LOGIN')) {
      return 'bg-emerald-500/10 text-emerald-500 border-emerald-500/20';
    }
    if (action.includes('UPDATE')) {
      return 'bg-blue-500/10 text-blue-500 border-blue-500/20';
    }
    return 'bg-background-alt text-text-secondary border-border';
  };

  const renderDataView = (data: any) => {
    if (!data) return <span className="text-text-muted italic text-[0.65rem] uppercase tracking-widest font-black">None</span>;
    try {
      const parsed = typeof data === 'string' ? JSON.parse(data) : data;
      return (
        <pre className="bg-slate-900 text-slate-300 p-4 rounded-xl text-xs overflow-auto max-h-40 font-mono border border-slate-800 shadow-inner custom-scrollbar">
          {JSON.stringify(parsed, null, 2)}
        </pre>
      );
    } catch (e) {
      return <span className="text-xs break-all font-mono text-text-secondary">{data}</span>;
    }
  };

  return (
    <div className="space-y-10 animate-in fade-in duration-700 pb-10">
      {/* Header Section */}
      <div className="flex flex-col md:flex-row justify-between items-start md:items-center gap-6">
        <div>
          <h2 className="text-3xl font-black text-text tracking-tight uppercase">System Audit</h2>
          <nav className="flex text-[0.65rem] font-black uppercase tracking-[2px] text-text-muted gap-2 items-center mt-1">
            <span>Security</span>
            <ChevronRight size={12} className="text-text-muted/30" />
            <span className="text-primary">Event Logs</span>
          </nav>
        </div>
        <div className="flex gap-3">
          <div className="flex items-center gap-2 px-5 py-2.5 bg-emerald-50 dark:bg-emerald-900/20 text-emerald-600 dark:text-emerald-400 border border-emerald-100 dark:border-emerald-900/30 rounded-xl font-bold text-sm shadow-sm cursor-default">
            <ShieldCheck size={18} />
            <span>Tracking {total.toLocaleString()} Events</span>
          </div>
        </div>
      </div>

      {/* Control Bar */}
      <div className="bg-card border border-border rounded-[2rem] p-3 shadow-sm flex flex-col lg:flex-row items-stretch lg:items-center gap-4">
        <div className="relative group flex-1">
          <Search size={18} className="absolute left-4 top-1/2 -translate-y-1/2 text-text-muted group-focus-within:text-primary transition-colors" />
          <input 
            type="text" 
            className="w-full bg-background-alt/50 border border-border rounded-2xl pl-11 pr-4 py-3.5 text-sm font-medium focus:outline-none focus:ring-4 focus:ring-primary/5 focus:bg-card focus:border-primary transition-all"
            placeholder="Search events by operator email..."
            value={filters.user_email}
            onChange={e => setFilters({ ...filters, user_email: e.target.value })}
          />
        </div>
        <div className="flex-1">
          <select
            className="w-full bg-background-alt/50 border border-border rounded-2xl px-4 py-3.5 text-sm font-medium focus:outline-none focus:ring-4 focus:ring-primary/5 focus:bg-card focus:border-primary transition-all cursor-pointer appearance-none"
            value={filters.action}
            onChange={(e) => setFilters({ ...filters, action: e.target.value })}
          >
            <option value="">All Security Events</option>
            <option value="LOGIN_SUCCESS">Authentication Success</option>
            <option value="LOGIN_FAILED">Authentication Failed</option>
            <option value="CREATE_USER">Operator Provisioned</option>
            <option value="UPDATE_USER">Operator Modified</option>
            <option value="DELETE_USER">Operator Revoked</option>
            <option value="CREATE_ENROLLMENT">Enrollment Created</option>
            <option value="PROCESS_PAYMENT">Payment Processed</option>
          </select>
        </div>
        <div className="flex-1">
          <select
            className="w-full bg-background-alt/50 border border-border rounded-2xl px-4 py-3.5 text-sm font-medium focus:outline-none focus:ring-4 focus:ring-primary/5 focus:bg-card focus:border-primary transition-all cursor-pointer appearance-none"
            value={filters.entity_type}
            onChange={(e) => setFilters({ ...filters, entity_type: e.target.value })}
          >
            <option value="">All System Domains</option>
            <option value="auth">Authentication</option>
            <option value="user">User Directory</option>
            <option value="enrollment">Academic Enrollment</option>
            <option value="payment">Financial Gateway</option>
            <option value="fee">Fee Structures</option>
            <option value="settings">System Parameters</option>
          </select>
        </div>
      </div>

      {/* Audit Log Table */}
      <div className="bg-card border border-border rounded-[2.5rem] shadow-sm overflow-hidden border-collapse">
        <div className="p-6 bg-background-alt/50 border-b border-border flex justify-between items-center">
            <div className="flex items-center gap-3">
                <div className="w-10 h-10 rounded-xl bg-primary/10 text-primary flex items-center justify-center shadow-sm">
                    <History size={20} />
                </div>
                <div>
                    <h3 className="text-lg font-black text-text tracking-tight">Security Event Feed</h3>
                    <p className="text-[0.65rem] text-text-muted font-bold uppercase tracking-widest">Audit Trail</p>
                </div>
            </div>
            <button 
                onClick={() => fetchLogs(filters)}
                className="p-2 text-text-muted hover:text-primary transition-colors hover:bg-background-alt rounded-lg"
            >
                <Activity size={18} />
            </button>
        </div>
        <div className="overflow-x-auto">
          <table className="w-full text-left">
            <thead>
              <tr className="bg-background-alt/50 border-b border-border">
                <th className="px-8 py-5 text-[0.65rem] font-black text-primary uppercase tracking-widest">Timestamp</th>
                <th className="px-8 py-5 text-[0.65rem] font-black text-primary uppercase tracking-widest">Operator</th>
                <th className="px-8 py-5 text-[0.65rem] font-black text-primary uppercase tracking-widest">Event Trigger</th>
                <th className="px-8 py-5 text-[0.65rem] font-black text-primary uppercase tracking-widest">Domain</th>
                <th className="px-8 py-5 text-[0.65rem] font-black text-primary uppercase tracking-widest text-right">Inspection</th>
              </tr>
            </thead>
            <tbody className="divide-y divide-border/50">
              {isLoading ? (
                <tr>
                  <td colSpan={5} className="py-20 text-center">
                    <div className="w-10 h-10 border-4 border-primary border-t-transparent rounded-full animate-spin mx-auto mb-4"></div>
                    <p className="text-text-muted font-bold uppercase tracking-widest text-[0.65rem]">Scanning security logs...</p>
                  </td>
                </tr>
              ) : logs.length === 0 ? (
                <tr>
                  <td colSpan={5} className="py-24 text-center">
                    <ShieldCheck size={48} className="mx-auto text-text-muted/30 mb-4" />
                    <p className="text-text-muted font-bold uppercase tracking-widest text-[0.65rem]">No events match criteria</p>
                  </td>
                </tr>
              ) : logs.map((log) => (
                <tr key={log.id} className="hover:bg-background-alt/40 transition-colors group cursor-default">
                  <td className="px-8 py-5">
                    <div className="text-[0.85rem] font-bold text-text">
                        {new Date(log.created_at).toLocaleDateString('en-US', { month: 'short', day: 'numeric', year: 'numeric' })}
                    </div>
                    <div className="text-[0.65rem] text-text-muted font-mono tracking-wider mt-0.5">
                        {new Date(log.created_at).toLocaleTimeString()}
                    </div>
                  </td>
                  <td className="px-8 py-5">
                    <div className="flex items-center gap-3">
                      <div className="w-8 h-8 rounded-full bg-background-alt border border-border flex items-center justify-center text-text-muted flex-shrink-0">
                        <User size={12} />
                      </div>
                      <div className="max-w-[150px] sm:max-w-xs">
                        <p className="text-[0.8rem] font-bold text-text truncate" title={log.user_email || 'System Operation'}>
                            {log.user_email || 'System Operation'}
                        </p>
                        <p className="text-[0.65rem] font-mono text-text-muted mt-0.5">{log.ip_address || 'Internal'}</p>
                      </div>
                    </div>
                  </td>
                  <td className="px-8 py-5">
                    <span className={`px-2.5 py-1 rounded-md text-[0.6rem] font-black uppercase tracking-widest border ${getActionColor(log.action)}`}>
                        {log.action.replace(/_/g, ' ')}
                    </span>
                  </td>
                  <td className="px-8 py-5">
                    <div className="flex items-center gap-1.5 text-[0.7rem] font-bold text-text-secondary uppercase tracking-widest">
                      <Database size={12} className="text-text-muted" />
                      {log.entity_type || 'GLOBAL'} 
                      {log.entity_id && <span className="opacity-50">#{log.entity_id}</span>}
                    </div>
                  </td>
                  <td className="px-8 py-5 text-right">
                    <button
                      onClick={() => setSelectedLog(log)}
                      className="p-2 bg-card border border-border text-text-muted hover:text-primary hover:border-primary rounded-xl transition-all shadow-sm opacity-0 group-hover:opacity-100"
                      title="Inspect Event Data"
                    >
                      <Eye size={16} />
                    </button>
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      </div>

      {/* Payload Inspection Modal */}
      {selectedLog && (
        <Modal
          open={true}
          onClose={() => setSelectedLog(null)}
          title="Event Inspection"
          icon={Activity}
          maxWidth="max-w-3xl"
          zIndex={150}
        >
          <ModalBody className="p-0">
            <div className="px-8 py-6 bg-background-alt/50 border-b border-border flex justify-between items-center relative overflow-hidden shrink-0">
              <div className="absolute right-[-20px] top-[-20px] opacity-[0.03] rotate-12">
                <ShieldCheck size={180} />
              </div>
              <div className="relative z-10">
                <h2 className="text-xl font-black text-text tracking-tight uppercase flex items-center gap-2">
                  <Activity className="text-primary" />
                  Event Inspection
                </h2>
                <p className="text-xs font-bold text-text-muted uppercase tracking-widest mt-1">Audit Record #{selectedLog.id}</p>
              </div>
            </div>
            <div className="p-8 overflow-y-auto custom-scrollbar space-y-6">
              <div className="grid grid-cols-2 gap-4">
                <div className="bg-background-alt/30 p-4 rounded-2xl border border-border">
                  <p className="text-[0.6rem] font-black uppercase tracking-widest text-text-muted mb-1">Operator</p>
                  <p className="text-sm font-bold text-text">{selectedLog.user_email || 'System Operation'}</p>
                  <p className="text-[0.65rem] font-mono text-text-muted mt-1">IP: {selectedLog.ip_address || 'Internal'}</p>
                </div>
                <div className="bg-background-alt/30 p-4 rounded-2xl border border-border">
                  <p className="text-[0.6rem] font-black uppercase tracking-widest text-text-muted mb-1">Event Domain</p>
                  <p className="text-sm font-bold text-text uppercase tracking-wider">{selectedLog.entity_type || 'GLOBAL'}</p>
                  {selectedLog.entity_id && (
                    <p className="text-[0.65rem] font-mono text-text-muted mt-1">Target ID: {selectedLog.entity_id}</p>
                  )}
                </div>
              </div>

              <div className="bg-background-alt/30 p-4 rounded-2xl border border-border flex items-center justify-between">
                <div>
                  <p className="text-[0.6rem] font-black uppercase tracking-widest text-text-muted mb-1">Action Triggered</p>
                  <span className={`px-2.5 py-1 rounded-md text-[0.6rem] font-black uppercase tracking-widest border ${getActionColor(selectedLog.action)}`}>
                    {selectedLog.action}
                  </span>
                </div>
                <div className="text-right">
                  <p className="text-[0.6rem] font-black uppercase tracking-widest text-text-muted mb-1">Timestamp</p>
                  <p className="text-xs font-bold text-text">{new Date(selectedLog.created_at).toLocaleString()}</p>
                </div>
              </div>

              <div className="space-y-4 pt-4 border-t border-border">
                <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
                  {(selectedLog.old_data || ['UPDATE', 'DELETE'].some(a => selectedLog.action.includes(a))) && (
                    <div className="space-y-2">
                      <h4 className="text-[0.65rem] font-black uppercase tracking-[2px] text-text-muted flex items-center gap-2">
                        <div className="w-2 h-2 rounded-full bg-rose-500"></div> Previous State
                      </h4>
                      {renderDataView(selectedLog.old_data)}
                    </div>
                  )}

                  {(selectedLog.new_data || ['UPDATE', 'CREATE', 'LOGIN'].some(a => selectedLog.action.includes(a))) && (
                    <div className="space-y-2">
                      <h4 className="text-[0.65rem] font-black uppercase tracking-[2px] text-text-muted flex items-center gap-2">
                        <div className="w-2 h-2 rounded-full bg-emerald-500"></div> Captured State
                      </h4>
                      {renderDataView(selectedLog.new_data)}
                    </div>
                  )}
                </div>
              </div>
            </div>
          </ModalBody>
        </Modal>
      )}
    </div>
  );
};

export default AuditLogs;