import React, { useEffect, useState } from 'react';
import { 
  RefreshCw, Database, CheckCircle2, AlertTriangle, 
  Search, X, Download, Filter, ChevronRight, 
  Activity, ArrowDownUp, HardDrive
} from 'lucide-react';
import { useSyncLogsStore } from '../../store/syncLogs';

const SyncLogs: React.FC = () => {
  const { logs, isLoading, fetchLogs } = useSyncLogsStore();
  const [searchQuery, setSearchQuery] = useState('');

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

  const filteredLogs = logs.filter(log => 
    log.table_name.toLowerCase().includes(searchQuery.toLowerCase()) ||
    log.operation.toLowerCase().includes(searchQuery.toLowerCase()) ||
    log.status.toLowerCase().includes(searchQuery.toLowerCase())
  );

  const stats = [
    { label: 'Total Operations', value: logs.length, icon: ArrowDownUp, color: 'blue', trend: 'Lifetime' },
    { label: 'Successful Syncs', value: logs.filter(l => l.status === 'success').length, icon: CheckCircle2, color: 'emerald', trend: 'Verified' },
    { label: 'Sync Errors', value: logs.filter(l => l.status === 'error' || l.status === 'failed').length, icon: AlertTriangle, color: 'rose', trend: 'Requires Attention' },
    { label: 'Active Tables', value: new Set(logs.map(l => l.table_name)).size, icon: HardDrive, color: 'purple', trend: 'Tracked' },
  ];

  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">Synchronization Core</h2>
          <nav className="flex text-[0.65rem] font-black uppercase tracking-[2px] text-text-muted gap-2 items-center mt-1">
            <span>System Logs</span>
            <ChevronRight size={12} className="text-text-muted/30" />
            <span className="text-primary">Data Integrity</span>
          </nav>
        </div>
        <div className="flex gap-3">
          <button className="flex items-center gap-2 px-5 py-2.5 bg-card border border-border text-text rounded-xl font-bold text-sm hover:bg-background-alt transition-all shadow-sm active:scale-95">
            <Download size={18} />
            Export Dump
          </button>
          <button 
            className="flex items-center gap-2 px-6 py-2.5 bg-primary text-white rounded-xl font-bold text-sm hover:bg-primary-dark transition-all shadow-lg shadow-primary/10 active:scale-95"
            onClick={() => fetchLogs()}
            disabled={isLoading}
          >
            <RefreshCw size={18} className={isLoading ? 'animate-spin' : ''} />
            {isLoading ? 'Syncing...' : 'Force Refresh'}
          </button>
        </div>
      </div>

      {/* Stats Bento Grid */}
      <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-4">
        {stats.map((stat) => (
          <div key={stat.label} className="bg-card border border-border p-5 rounded-2xl flex items-center gap-4 hover:shadow-md transition-all group cursor-default">
            <div className={`w-12 h-12 rounded-2xl flex items-center justify-center border group-hover:scale-110 transition-transform
              ${stat.color === 'blue' ? 'bg-blue-50 dark:bg-blue-900/20 text-blue-600 dark:text-blue-400 border-blue-100 dark:border-blue-900/30' : 
                stat.color === 'emerald' ? 'bg-emerald-50 dark:bg-emerald-900/20 text-emerald-600 dark:text-emerald-400 border-emerald-100 dark:border-emerald-900/30' : 
                stat.color === 'rose' ? 'bg-rose-50 dark:bg-rose-900/20 text-rose-600 dark:text-rose-400 border-rose-100 dark:border-rose-900/30' : 
                'bg-purple-50 dark:bg-purple-900/20 text-purple-600 dark:text-purple-400 border-purple-100 dark:border-purple-900/30'}`}>
              <stat.icon size={22} />
            </div>
            <div>
              <p className="text-[0.65rem] font-black uppercase tracking-wider text-text-muted">{stat.label}</p>
              <div className="flex items-baseline gap-2">
                <p className="text-2xl font-black text-text">{stat.value}</p>
                <span className="text-[0.6rem] font-bold text-text-muted">{stat.trend}</span>
              </div>
            </div>
          </div>
        ))}
      </div>

      {/* Control Bar */}
      <div className="bg-card border border-border rounded-[2rem] p-2 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 text-sm font-medium focus:outline-none focus:ring-4 focus:ring-primary/5 focus:bg-card focus:border-primary transition-all"
            placeholder="Search logs by table, operation, or status..."
            value={searchQuery}
            onChange={e => setSearchQuery(e.target.value)}
          />
          {searchQuery && (
            <button onClick={() => setSearchQuery('')} className="absolute right-4 top-1/2 -translate-y-1/2 text-text-muted hover:text-rose-500">
              <X size={16} />
            </button>
          )}
        </div>
        <button className="px-5 py-3 bg-background-alt/50 hover:bg-background-alt text-text-muted rounded-2xl border border-border transition-all flex items-center justify-center gap-2">
          <Filter size={18} />
          <span className="text-[0.7rem] font-black uppercase tracking-widest">Filter Logs</span>
        </button>
      </div>

      {/* Sync 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">
                    <Activity size={20} />
                </div>
                <div>
                    <h3 className="text-lg font-black text-text tracking-tight">Sync Log</h3>
                    <p className="text-[0.65rem] text-text-muted font-bold uppercase tracking-widest">Offline-to-cloud sync history</p>
                </div>
            </div>
            <span className="px-3 py-1 bg-emerald-500/10 text-emerald-500 border border-emerald-500/20 rounded-full text-[0.65rem] font-black uppercase tracking-widest flex items-center gap-2">
                <span className="w-1.5 h-1.5 bg-emerald-500 rounded-full animate-pulse"></span>
                Live Polling
            </span>
        </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">Target Table</th>
                <th className="px-8 py-5 text-[0.65rem] font-black text-primary uppercase tracking-widest">Operation</th>
                <th className="px-8 py-5 text-[0.65rem] font-black text-primary uppercase tracking-widest">Record ID</th>
                <th className="px-8 py-5 text-[0.65rem] font-black text-primary uppercase tracking-widest text-right">Status</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]">Fetching system logs...</p>
                  </td>
                </tr>
              ) : filteredLogs.length === 0 ? (
                <tr>
                  <td colSpan={5} className="py-24 text-center">
                    <Database 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 synchronization logs found</p>
                  </td>
                </tr>
              ) : filteredLogs.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-2">
                      <div className="w-8 h-8 rounded-lg bg-primary/10 text-primary flex items-center justify-center group-hover:scale-110 transition-transform">
                          <Database size={14} />
                      </div>
                      <span className="text-[0.8rem] font-bold text-text group-hover:text-primary transition-colors capitalize">
                          {log.table_name.replace('_', ' ')}
                      </span>
                    </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
                        ${log.operation === 'INSERT' ? 'bg-emerald-500/10 text-emerald-500 border-emerald-500/20' : 
                          log.operation === 'UPDATE' ? 'bg-blue-500/10 text-blue-500 border-blue-500/20' : 
                          log.operation === 'DELETE' ? 'bg-rose-500/10 text-rose-500 border-rose-500/20' : 
                          'bg-background-alt text-text-secondary border-border'}`}>
                        {log.operation}
                    </span>
                  </td>
                  <td className="px-8 py-5">
                    <span className="text-[0.7rem] font-mono font-bold text-text-secondary bg-background-alt px-2 py-1 rounded border border-border">
                        {log.record_id || 'NULL'}
                    </span>
                  </td>
                  <td className="px-8 py-5 text-right">
                    {log.status === 'success' ? (
                      <span className="inline-flex items-center gap-1.5 px-3 py-1.5 bg-emerald-50 dark:bg-emerald-900/20 text-emerald-600 dark:text-emerald-400 rounded-xl border border-emerald-100 dark:border-emerald-900/30 text-[0.65rem] font-black uppercase tracking-widest ml-auto">
                        <CheckCircle2 size={14} />
                        Success
                      </span>
                    ) : (
                      <span className="inline-flex items-center gap-1.5 px-3 py-1.5 bg-rose-50 dark:bg-rose-900/20 text-rose-600 dark:text-rose-400 rounded-xl border border-rose-100 dark:border-rose-900/30 text-[0.65rem] font-black uppercase tracking-widest ml-auto shadow-sm">
                        <AlertTriangle size={14} />
                        {log.status}
                      </span>
                    )}
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      </div>
    </div>
  );
};

export default SyncLogs;
