import { useState, useEffect } from 'react';
import api from '../../store/auth';
import { 
  Database, Activity, Users, Settings, 
  Server, ShieldCheck, ArrowUpRight, Clock,
  HardDrive, AlertTriangle, Play, Sparkles,
  CheckCircle2, AlertCircle, Loader2, X, RefreshCw,
  Terminal, Search, Copy, Check, Download
} from 'lucide-react';
import { Link } from 'react-router-dom';
import { Modal } from '../../components/ui/Modal';
import LicenseSourceBanner from '../../components/LicenseSourceBanner';

export default function SysAdminDashboard() {
  const [stats, setStats] = useState<any>(null);
  const [runningDiagnostics, setRunningDiagnostics] = useState(false);
  const [diagnosticResults, setDiagnosticResults] = useState<any>(null);
  const [showLogs, setShowLogs] = useState(false);
  const [serverLogs, setServerLogs] = useState<any[]>([]);
  const [loadingLogs, setLoadingLogs] = useState(false);
  const [logFilterLevel, setLogFilterLevel] = useState<'ALL' | 'INFO' | 'WARN' | 'ERROR'>('ALL');
  const [logSearchQuery, setLogSearchQuery] = useState('');
  const [logCopied, setLogCopied] = useState(false);
  const [tracingSync, setTracingSync] = useState(false);
  const [syncTrace, setSyncTrace] = useState<string[]>([]);

  const handleViewLogs = async () => {
    setShowLogs(true);
    setLoadingLogs(true);
    try {
      const response = await api.get('/sysadmin/logs');
      setServerLogs(response.data);
    } catch (err) {
      console.error('Failed to fetch logs:', err);
    } finally {
      setLoadingLogs(false);
    }
  };

  const filteredLogs = serverLogs.filter(log => {
    const matchesLevel = logFilterLevel === 'ALL' || log.level === logFilterLevel;
    const matchesSearch = !logSearchQuery || 
      (log.message && log.message.toLowerCase().includes(logSearchQuery.toLowerCase())) ||
      (log.source && log.source.toLowerCase().includes(logSearchQuery.toLowerCase()));
    return matchesLevel && matchesSearch;
  });

  const handleCopyLogs = () => {
    const text = filteredLogs.map(l => `[${new Date(l.timestamp).toISOString()}] [${l.level || 'INFO'}] [${l.source || 'Server'}]: ${l.message}`).join('\n');
    navigator.clipboard.writeText(text);
    setLogCopied(true);
    setTimeout(() => setLogCopied(false), 2000);
  };

  const handleDownloadLogs = () => {
    const text = filteredLogs.map(l => `[${new Date(l.timestamp).toISOString()}] [${l.level || 'INFO'}] [${l.source || 'Server'}]: ${l.message}`).join('\n');
    const blob = new Blob([text], { type: 'text/plain;charset=utf-8' });
    const url = URL.createObjectURL(blob);
    const link = document.createElement('a');
    link.href = url;
    link.download = `server_logs_${new Date().toISOString().slice(0, 10)}.log`;
    link.click();
    URL.revokeObjectURL(url);
  };

  const handleRunDiagnostics = async () => {
    setRunningDiagnostics(true);
    setDiagnosticResults(null);
    try {
      const response = await api.get('/sysadmin/diagnostics');
      setDiagnosticResults(response.data);
    } catch (err) {
      console.error('Diagnostics failed:', err);
    } finally {
      setRunningDiagnostics(false);
    }
  };

  const handleRunSyncTrace = async () => {
    setTracingSync(true);
    setSyncTrace([]);
    try {
      const res = await api.post('/sysadmin/sync/trace');
      if (res.data.trace) {
        setSyncTrace(res.data.trace);
      }
    } catch (err: any) {
      const errorMsg = err.response?.data?.error || err.message;
      setSyncTrace(prev => [...prev, `[${new Date().toLocaleTimeString()}] ❌ Failed to execute trace: ${errorMsg}`]);
    } finally {
      setTracingSync(false);
    }
  };

  useEffect(() => {
    const fetchStats = async () => {
      try {
        const response = await api.get('/sysadmin/stats');
        setStats(response.data);
      } catch (err) {
        console.error('Failed to fetch sysadmin stats:', err);
        // Fallback or error handling
      }
    };

    fetchStats();
    const interval = setInterval(fetchStats, 30000); // Refresh every 30s
    return () => clearInterval(interval);
  }, []);

  if (!stats) return (
    <div className="flex flex-col justify-center items-center h-[60vh] gap-4">
      <div className="w-12 h-12 border-4 border-primary border-t-transparent rounded-full animate-spin"></div>
      <p className="text-text-muted font-medium animate-pulse">Scanning System Architecture...</p>
    </div>
  );

  return (
    <div className="space-y-8 animate-in fade-in duration-500 pb-10">
      {/* Header Section */}
      <div className="flex flex-col md:flex-row md:items-end justify-between gap-4">
        <div>
          <h1 className="text-3xl font-extrabold text-text tracking-tight uppercase">Infrastructure</h1>
          <p className="text-text-muted mt-1 text-sm font-medium">Technical Command & Telemetry Dashboard</p>
        </div>
        <div className="flex items-center gap-3">
          <div className={`flex items-center gap-2 px-4 py-2 ${stats.statusColor === 'emerald' ? 'bg-emerald-50 dark:bg-emerald-900/20 border-emerald-100 dark:border-emerald-900/30 text-emerald-600 dark:text-emerald-400' : stats.statusColor === 'rose' ? 'bg-rose-50 dark:bg-rose-900/20 border-rose-100 dark:border-rose-900/30 text-rose-600 dark:text-rose-400' : 'bg-amber-50 dark:bg-amber-900/20 border-amber-100 dark:border-amber-900/30 text-amber-600 dark:text-amber-400'} border rounded-xl font-bold text-xs shadow-sm cursor-default transition-colors duration-500`}>
            <span className="relative flex h-2 w-2">
              <span className={`animate-ping absolute inline-flex h-full w-full rounded-full ${stats.statusColor === 'emerald' ? 'bg-emerald-400' : stats.statusColor === 'rose' ? 'bg-rose-400' : 'bg-amber-400'} opacity-75`}></span>
              <span className={`relative inline-flex rounded-full h-2 w-2 ${stats.statusColor === 'emerald' ? 'bg-emerald-500' : stats.statusColor === 'rose' ? 'bg-rose-500' : 'bg-amber-500'}`}></span>
            </span>
            {stats.systemStatus || 'System Online'}
          </div>
          <button 
            onClick={handleRunDiagnostics}
            disabled={runningDiagnostics}
            className="flex items-center gap-2 bg-primary hover:bg-primary-dark disabled:opacity-50 text-white px-5 py-2.5 rounded-xl font-semibold transition-all shadow-lg shadow-primary/10 active:scale-[0.98]"
          >
            {runningDiagnostics ? <Loader2 size={18} className="animate-spin" /> : <Play size={18} />}
            <span>{runningDiagnostics ? 'Running...' : 'Run Diagnostics'}</span>
          </button>
        </div>
      </div>

      <LicenseSourceBanner />

      {/* Diagnostics Results */}
      {diagnosticResults && (
        <div className="bg-card border border-border rounded-3xl p-6 shadow-sm animate-in slide-in-from-top duration-300">
          <div className="flex items-center justify-between mb-6">
            <div className="flex items-center gap-3">
              <div className={`p-2 rounded-lg ${diagnosticResults.overallStatus === 'PASS' ? 'bg-emerald-500/10 text-emerald-500' : diagnosticResults.overallStatus === 'WARN' ? 'bg-amber-500/10 text-amber-500' : 'bg-rose-500/10 text-rose-500'}`}>
                <ShieldCheck size={20} />
              </div>
              <div>
                <h3 className="text-sm font-black text-text uppercase tracking-wider">Diagnostic Report</h3>
                <p className="text-[0.6rem] text-text-muted font-bold uppercase tracking-widest mt-0.5">
                  Result: <span className={diagnosticResults.overallStatus === 'PASS' ? 'text-emerald-500' : diagnosticResults.overallStatus === 'WARN' ? 'text-amber-500' : 'text-rose-500'}>{diagnosticResults.overallStatus}</span>
                </p>
              </div>
            </div>
            <button 
              onClick={() => setDiagnosticResults(null)}
              className="text-[0.6rem] font-black uppercase tracking-widest text-text-muted hover:text-text transition-colors"
            >
              Clear Report
            </button>
          </div>

          <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
            {diagnosticResults.checks.map((check: any, idx: number) => (
              <div key={idx} className="flex items-start gap-3 p-4 bg-background-alt/30 rounded-2xl border border-border/50">
                <div className="mt-0.5">
                  {check.status === 'PASS' ? (
                    <CheckCircle2 size={16} className="text-emerald-500" />
                  ) : check.status === 'WARN' ? (
                    <AlertTriangle size={16} className="text-amber-500" />
                  ) : (
                    <AlertCircle size={16} className="text-rose-500" />
                  )}
                </div>
                <div>
                  <p className="text-xs font-bold text-text">{check.name}</p>
                  <p className="text-[0.65rem] text-text-muted mt-0.5 leading-relaxed">{check.message}</p>
                </div>
              </div>
            ))}
          </div>
        </div>
      )}

      {/* Telemetry Grid */}
      <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-4">
        <div className="bg-card border border-border p-6 rounded-3xl shadow-sm hover:border-primary transition-colors group cursor-default">
          <div className="flex justify-between items-start mb-4">
            <div className="p-2.5 rounded-xl bg-blue-500/10 text-blue-500">
              <HardDrive size={22} />
            </div>
          </div>
          <p className="text-[0.65rem] font-black uppercase tracking-[2px] text-text-muted mb-1">Database Size</p>
          <h3 className="text-3xl font-black text-text tracking-tight">{stats.dbSize}</h3>
          <p className="text-[0.65rem] mt-2 italic font-bold text-text-muted">
            {stats.isWal ? 'SQLite WAL Mode Active' : 'SQLite Rollback Mode'}
          </p>
        </div>

        <div className="bg-card border border-border p-6 rounded-3xl shadow-sm hover:border-primary transition-colors group cursor-default">
          <div className="flex justify-between items-start mb-4">
            <div className="p-2.5 rounded-xl bg-emerald-500/10 text-emerald-500">
              <Activity size={22} />
            </div>
          </div>
          <p className="text-[0.65rem] font-black uppercase tracking-[2px] text-text-muted mb-1">API Latency</p>
          <h3 className="text-3xl font-black text-text tracking-tight">{stats.apiLatency}</h3>
          <p className="text-[0.65rem] mt-2 italic font-bold text-emerald-500">Optimal Response Time</p>
        </div>

        <div className="bg-card border border-border p-6 rounded-3xl shadow-sm hover:border-primary transition-colors group cursor-default">
          <div className="flex justify-between items-start mb-4">
            <div className="p-2.5 rounded-xl bg-purple-500/10 text-purple-500">
              <Users size={22} />
            </div>
          </div>
          <p className="text-[0.65rem] font-black uppercase tracking-[2px] text-text-muted mb-1">Active Sessions</p>
          <h3 className="text-3xl font-black text-text tracking-tight">{stats.activeSessions}</h3>
          <p className="text-[0.65rem] mt-2 italic font-bold text-text-muted">Concurrent Connections</p>
        </div>

        <div className="bg-card border border-border p-6 rounded-3xl shadow-sm hover:border-primary transition-colors group cursor-default">
          <div className="flex justify-between items-start mb-4">
            <div className="p-2.5 rounded-xl bg-rose-500/10 text-rose-500">
              <AlertTriangle size={22} />
            </div>
          </div>
          <p className="text-[0.65rem] font-black uppercase tracking-[2px] text-text-muted mb-1">Sync Conflicts</p>
          <h3 className="text-3xl font-black text-rose-500 tracking-tight">{stats.syncErrors}</h3>
          <p className="text-[0.65rem] mt-2 italic font-bold text-rose-500">Requires manual resolution</p>
        </div>
      </div>

      <div className="grid grid-cols-1 lg:grid-cols-3 gap-6">
        {/* Left Column (2/3) */}
        <div className="lg:col-span-2 space-y-6">
          
          {/* Server Resources Box */}
          <div className="bg-card rounded-[2.5rem] border border-border overflow-hidden shadow-sm p-8">
            <div className="flex items-center gap-4 mb-8">
              <div className="w-12 h-12 rounded-2xl bg-primary/10 text-primary flex items-center justify-center shadow-sm">
                  <Server size={24} />
              </div>
              <div>
                  <h3 className="text-xl font-black text-text tracking-tight uppercase">Server Resources</h3>
                  <p className="text-[0.65rem] text-text-muted font-bold uppercase tracking-widest mt-1">Host Telemetry Data</p>
              </div>
            </div>

            <div className="grid grid-cols-1 md:grid-cols-2 gap-8">
              {/* CPU Usage */}
              <div className="space-y-3">
                <div className="flex justify-between items-end">
                  <span className="text-[0.65rem] font-black text-text-muted uppercase tracking-widest">CPU Utilization</span>
                  <span className="text-sm font-bold text-text">{stats.resources?.cpu?.usage || 0}%</span>
                </div>
                <div className="w-full bg-background-alt rounded-full h-2 overflow-hidden border border-border">
                  <div className="bg-primary h-full rounded-full transition-all duration-1000" style={{ width: `${stats.resources?.cpu?.usage || 0}%` }}></div>
                </div>
                <p className="text-[0.6rem] text-text-muted font-mono">{stats.resources?.cpu?.detail}</p>
              </div>

              {/* Memory Usage */}
              <div className="space-y-3">
                <div className="flex justify-between items-end">
                  <span className="text-[0.65rem] font-black text-text-muted uppercase tracking-widest">Memory (RAM)</span>
                  <span className="text-sm font-bold text-text">{stats.resources?.memory?.used} GB / {stats.resources?.memory?.total} GB</span>
                </div>
                <div className="w-full bg-background-alt rounded-full h-2 overflow-hidden border border-border">
                  <div className="bg-emerald-500 h-full rounded-full transition-all duration-1000" style={{ width: `${stats.resources?.memory?.percent || 0}%` }}></div>
                </div>
                <p className="text-[0.6rem] text-text-muted font-mono">{stats.resources?.memory?.percent}% Allocated</p>
              </div>

              {/* Disk Space */}
              <div className="space-y-3">
                <div className="flex justify-between items-end">
                  <span className="text-[0.65rem] font-black text-text-muted uppercase tracking-widest">Storage Volume</span>
                  <span className="text-sm font-bold text-text">{stats.resources?.storage?.used} / {stats.resources?.storage?.total}</span>
                </div>
                <div className="w-full bg-background-alt rounded-full h-2 overflow-hidden border border-border">
                  <div className="bg-blue-500 h-full rounded-full transition-all duration-1000" style={{ width: `${stats.resources?.storage?.percent || 0}%` }}></div>
                </div>
                <p className="text-[0.6rem] text-text-muted font-mono">{stats.resources?.storage?.detail}</p>
              </div>

              {/* Network */}
              <div className="space-y-3">
                <div className="flex justify-between items-end">
                  <span className="text-[0.65rem] font-black text-text-muted uppercase tracking-widest">Network I/O</span>
                  <span className="text-sm font-bold text-text">{stats.resources?.network?.io}</span>
                </div>
                <div className="w-full bg-background-alt rounded-full h-2 overflow-hidden border border-border">
                  <div className="bg-purple-500 h-full rounded-full transition-all duration-1000" style={{ width: '8%' }}></div>
                </div>
                <p className="text-[0.6rem] text-text-muted font-mono">{stats.resources?.network?.detail}</p>
              </div>
            </div>
          </div>

          {/* Quick Access Modules */}
          <div className="grid grid-cols-1 sm:grid-cols-3 gap-4">
            <Link to="/settings" className="bg-card border border-border p-5 rounded-2xl flex flex-col items-center justify-center text-center gap-3 hover:border-primary hover:bg-background-alt/50 transition-all group">
              <div className="p-3 bg-primary/10 text-primary rounded-xl group-hover:scale-110 transition-transform"><Settings size={20}/></div>
              <span className="text-xs font-bold text-text uppercase tracking-wider">Control Center</span>
            </Link>
            <Link to="/sync-logs" className="bg-card border border-border p-5 rounded-2xl flex flex-col items-center justify-center text-center gap-3 hover:border-blue-500 hover:bg-background-alt/50 transition-all group">
              <div className="p-3 bg-blue-500/10 text-blue-500 rounded-xl group-hover:scale-110 transition-transform"><Activity size={20}/></div>
              <span className="text-xs font-bold text-text uppercase tracking-wider">Sync Logs</span>
            </Link>
            <Link to="/audit-logs" className="bg-card border border-border p-5 rounded-2xl flex flex-col items-center justify-center text-center gap-3 hover:border-emerald-500 hover:bg-background-alt/50 transition-all group">
              <div className="p-3 bg-emerald-500/10 text-emerald-500 rounded-xl group-hover:scale-110 transition-transform"><ShieldCheck size={20}/></div>
              <span className="text-xs font-bold text-text uppercase tracking-wider">Audit Trail</span>
            </Link>
          </div>

          {/* Sync Engine Live Trace section */}
          <div className="bg-card border border-border rounded-[2.5rem] p-8 shadow-sm relative overflow-hidden mt-6 animate-in fade-in zoom-in-95 duration-500">
            <div className="flex flex-col sm:flex-row justify-between items-start sm:items-center gap-4 mb-6">
              <div className="flex items-center gap-3">
                <div className="p-3 rounded-2xl bg-blue-500/10 text-blue-500 border border-blue-500/20 shadow-sm">
                  <Database size={24} />
                </div>
                <div>
                  <h3 className="text-lg font-black text-text tracking-tight uppercase">Central DB Sync Trace</h3>
                  <p className="text-[0.65rem] font-black text-text-muted uppercase tracking-widest mt-1">Live Upload/Download Execution Observations</p>
                </div>
              </div>
              <button 
                onClick={handleRunSyncTrace}
                disabled={tracingSync}
                className="flex items-center gap-2 bg-primary hover:bg-primary-dark disabled:opacity-50 text-white px-5 py-2.5 rounded-xl font-bold text-xs shadow-md uppercase tracking-wider active:scale-95 transition-all"
              >
                {tracingSync ? <Loader2 size={14} className="animate-spin" /> : <RefreshCw size={14} />}
                <span>{tracingSync ? 'Running Sync Trace...' : 'Trigger Sync Trace'}</span>
              </button>
            </div>

            {syncTrace.length > 0 ? (
              <div className="bg-slate-900 border border-slate-800 rounded-3xl p-5 font-mono text-[0.7rem] text-slate-300 max-h-[300px] overflow-y-auto space-y-2.5 custom-scrollbar">
                {syncTrace.map((log, index) => {
                  const isError = log.includes('❌') || log.includes('ERROR') || log.includes('failed');
                  const isWarning = log.includes('⚠️');
                  const isSuccess = log.includes('✅') || log.includes('success');
                  return (
                    <div 
                      key={index} 
                      className={`py-1 border-b border-slate-800/40 last:border-0 ${
                        isError ? 'text-rose-400' : isWarning ? 'text-amber-400' : isSuccess ? 'text-emerald-400' : 'text-slate-300'
                      }`}
                    >
                      {log}
                    </div>
                  );
                })}
              </div>
            ) : (
              <div className="p-8 text-center text-text-muted bg-muted/20 border border-dashed border-border rounded-3xl">
                <Activity className="mx-auto mb-2 text-text-muted/30" size={32} />
                <p className="text-xs font-bold">No sync trace executed yet</p>
                <p className="text-[0.65rem] mt-1">Trigger a live trace to monitor conflict resolutions and central data transfers.</p>
              </div>
            )}
          </div>
        </div>

        {/* Right Column (1/3) */}
        <div className="space-y-6">
          
          {/* Uptime Box */}
          <div className="bg-slate-900 rounded-[2.5rem] p-8 text-white shadow-2xl relative overflow-hidden group">
            <div className="absolute right-[-40px] bottom-[-40px] opacity-10 group-hover:rotate-12 transition-transform duration-700">
                <Sparkles size={200} strokeWidth={1} />
            </div>
            <div className="relative z-10 text-center">
              <p className="text-[0.65rem] font-black uppercase tracking-[3px] text-white/40 mb-2">System Uptime</p>
              <h4 className="text-5xl font-black mb-6 tracking-tighter text-emerald-400">{stats.uptime}</h4>
              
              <div className="bg-white/10 rounded-2xl p-4 border border-white/5 text-left mb-6">
                <div className="flex items-center gap-2 mb-2">
                  <Clock size={14} className="text-white/40" />
                  <span className="text-xs font-bold text-white/80">Process Uptime</span>
                </div>
                <p className="text-[0.7rem] font-mono text-white/60">{stats.uptimeDetail || 'N/A'}</p>
              </div>

              <button 
                onClick={handleViewLogs}
                className="w-full py-3.5 bg-white/10 hover:bg-white/20 text-white rounded-xl text-[0.65rem] font-black uppercase tracking-widest transition-all border border-white/10"
              >
                View Server Logs
              </button>
            </div>
          </div>

          {/* Server Logs Modal */}
          {showLogs && (
            <Modal
              open={true}
              onClose={() => setShowLogs(false)}
              title="Server Runtime Telemetry"
              subtitle="Real-time System Audit & Execution Logs"
              icon={Terminal}
              watermarkIcon={Terminal}
              maxWidth="max-w-5xl"
              zIndex={150}
              bodyClassName="p-0 bg-[#0B0F19] text-slate-100 flex flex-col min-h-[480px]"
            >
              {/* Terminal Window Header Bar */}
              <div className="flex flex-wrap items-center justify-between gap-3 px-4 py-3 bg-[#111827] border-b border-slate-800/80">
                <div className="flex items-center gap-2">
                  <div className="flex items-center gap-1.5 mr-2">
                    <span className="w-3 h-3 rounded-full bg-rose-500/80 inline-block shadow-sm"></span>
                    <span className="w-3 h-3 rounded-full bg-amber-500/80 inline-block shadow-sm"></span>
                    <span className="w-3 h-3 rounded-full bg-emerald-500/80 inline-block shadow-sm"></span>
                  </div>
                  <span className="text-[0.7rem] font-mono text-slate-400 font-medium tracking-wide">
                    node@africa-alert-server:~# telemetry.log
                  </span>
                  <span className="inline-flex items-center gap-1 px-2 py-0.5 rounded-full bg-emerald-500/10 border border-emerald-500/20 text-emerald-400 text-[0.65rem] font-mono font-bold animate-pulse">
                    <span className="w-1.5 h-1.5 rounded-full bg-emerald-400"></span>
                    LIVE STREAM
                  </span>
                </div>

                {/* Log Quick Actions */}
                <div className="flex items-center gap-2">
                  <button
                    onClick={handleViewLogs}
                    disabled={loadingLogs}
                    className="flex items-center gap-1.5 px-3 py-1.5 bg-slate-800 hover:bg-slate-700 text-slate-200 rounded-lg text-xs font-mono transition-colors border border-slate-700/60 disabled:opacity-50"
                    title="Refresh logs"
                  >
                    <RefreshCw size={13} className={loadingLogs ? 'animate-spin text-emerald-400' : ''} />
                    <span>Refresh</span>
                  </button>
                  <button
                    onClick={handleCopyLogs}
                    disabled={filteredLogs.length === 0}
                    className="flex items-center gap-1.5 px-3 py-1.5 bg-slate-800 hover:bg-slate-700 text-slate-200 rounded-lg text-xs font-mono transition-colors border border-slate-700/60 disabled:opacity-50"
                    title="Copy logs to clipboard"
                  >
                    {logCopied ? <Check size={13} className="text-emerald-400" /> : <Copy size={13} />}
                    <span>{logCopied ? 'Copied!' : 'Copy'}</span>
                  </button>
                  <button
                    onClick={handleDownloadLogs}
                    disabled={filteredLogs.length === 0}
                    className="flex items-center gap-1.5 px-3 py-1.5 bg-slate-800 hover:bg-slate-700 text-slate-200 rounded-lg text-xs font-mono transition-colors border border-slate-700/60 disabled:opacity-50"
                    title="Download log file"
                  >
                    <Download size={13} />
                    <span>Export</span>
                  </button>
                </div>
              </div>

              {/* Filter and Search Bar */}
              <div className="flex flex-wrap items-center justify-between gap-3 px-4 py-2.5 bg-[#0D1322] border-b border-slate-800/60 text-xs font-mono">
                {/* Search Input */}
                <div className="relative flex-1 min-w-[240px]">
                  <Search size={14} className="absolute left-3 top-1/2 -translate-y-1/2 text-slate-500" />
                  <input
                    type="text"
                    value={logSearchQuery}
                    onChange={(e) => setLogSearchQuery(e.target.value)}
                    placeholder="Search logs by message or source..."
                    className="w-full pl-9 pr-8 py-1.5 bg-slate-950/80 border border-slate-800 rounded-lg text-slate-200 placeholder-slate-500 focus:outline-none focus:border-indigo-500/80 text-xs font-mono"
                  />
                  {logSearchQuery && (
                    <button
                      onClick={() => setLogSearchQuery('')}
                      className="absolute right-2.5 top-1/2 -translate-y-1/2 text-slate-500 hover:text-slate-300"
                    >
                      <X size={13} />
                    </button>
                  )}
                </div>

                {/* Level Tabs */}
                <div className="flex items-center gap-1 bg-slate-950 p-1 rounded-lg border border-slate-800/80">
                  {(['ALL', 'INFO', 'WARN', 'ERROR'] as const).map((lvl) => {
                    const count = lvl === 'ALL'
                      ? serverLogs.length
                      : serverLogs.filter(l => l.level === lvl).length;
                    const isActive = logFilterLevel === lvl;
                    return (
                      <button
                        key={lvl}
                        onClick={() => setLogFilterLevel(lvl)}
                        className={`px-2.5 py-1 rounded-md text-[0.7rem] font-mono font-bold transition-colors flex items-center gap-1.5 ${
                          isActive
                            ? lvl === 'ERROR'
                              ? 'bg-rose-500/20 text-rose-300 border border-rose-500/40'
                              : lvl === 'WARN'
                              ? 'bg-amber-500/20 text-amber-300 border border-amber-500/40'
                              : lvl === 'INFO'
                              ? 'bg-emerald-500/20 text-emerald-300 border border-emerald-500/40'
                              : 'bg-indigo-600 text-white'
                            : 'text-slate-400 hover:text-slate-200 hover:bg-slate-900'
                        }`}
                      >
                        <span>{lvl}</span>
                        <span className={`px-1.5 py-0.2 rounded-full text-[0.6rem] ${
                          isActive ? 'bg-black/30' : 'bg-slate-800 text-slate-400'
                        }`}>
                          {count}
                        </span>
                      </button>
                    );
                  })}
                </div>
              </div>

              {/* Log Console Body */}
              <div className="flex-1 overflow-y-auto max-h-[55vh] p-4 space-y-1.5 font-mono text-[0.72rem] bg-[#070A12] leading-relaxed">
                {loadingLogs ? (
                  <div className="flex flex-col items-center justify-center py-20 gap-3">
                    <Loader2 size={28} className="text-indigo-400 animate-spin" />
                    <p className="text-slate-400 animate-pulse font-mono text-xs">Streaming logs from server host...</p>
                  </div>
                ) : filteredLogs.length > 0 ? (
                  filteredLogs.map((log, idx) => {
                    const isError = log.level === 'ERROR';
                    const isWarn = log.level === 'WARN';
                    return (
                      <div
                        key={idx}
                        className="flex items-start gap-3 p-1.5 px-2.5 rounded-md hover:bg-slate-900/90 transition-colors group border border-transparent hover:border-slate-800/50"
                      >
                        {/* Line number */}
                        <span className="text-slate-600 select-none text-[0.65rem] w-7 shrink-0 text-right pt-0.5">
                          {idx + 1}
                        </span>

                        {/* Timestamp */}
                        <span className="text-slate-500 shrink-0 font-mono text-[0.68rem] pt-0.5">
                          {new Date(log.timestamp).toLocaleTimeString([], { hour12: false, hour: '2-digit', minute: '2-digit', second: '2-digit' })}
                        </span>

                        {/* Level badge */}
                        <span
                          className={`shrink-0 px-2 py-0.5 rounded text-[0.62rem] font-bold tracking-wide uppercase ${
                            isError
                              ? 'bg-rose-500/15 text-rose-400 border border-rose-500/30 shadow-sm shadow-rose-950'
                              : isWarn
                              ? 'bg-amber-500/15 text-amber-400 border border-amber-500/30 shadow-sm shadow-amber-950'
                              : 'bg-emerald-500/15 text-emerald-400 border border-emerald-500/30 shadow-sm shadow-emerald-950'
                          }`}
                        >
                          {log.level || 'INFO'}
                        </span>

                        {/* Source tag */}
                        <span className="shrink-0 px-1.5 py-0.5 rounded bg-slate-800/70 text-slate-300 text-[0.65rem] border border-slate-700/50">
                          {log.source || 'Server'}
                        </span>

                        {/* Log message */}
                        <span className={`break-all ${
                          isError ? 'text-rose-200' : isWarn ? 'text-amber-200' : 'text-slate-200 group-hover:text-white'
                        }`}>
                          {log.message}
                        </span>
                      </div>
                    );
                  })
                ) : (
                  <div className="flex flex-col items-center justify-center py-16 text-slate-500 gap-2 font-mono text-xs">
                    <Terminal size={32} className="text-slate-700 mb-1" />
                    <p>No telemetry logs matched your current filter.</p>
                    {logSearchQuery && (
                      <button
                        onClick={() => setLogSearchQuery('')}
                        className="text-indigo-400 hover:underline mt-1 text-[0.7rem]"
                      >
                        Clear search query
                      </button>
                    )}
                  </div>
                )}
              </div>

              {/* Console Footer Status */}
              <div className="px-4 py-3 border-t border-slate-800/80 bg-[#0D1322] flex flex-wrap justify-between items-center gap-3">
                <div className="flex items-center gap-3 text-[0.65rem] font-mono text-slate-400">
                  <span>
                    Showing <strong className="text-slate-200">{filteredLogs.length}</strong> of{' '}
                    <strong className="text-slate-200">{serverLogs.length}</strong> logs
                  </span>
                  <span className="text-slate-600">|</span>
                  <span className="text-slate-500">Press Esc to exit</span>
                </div>
                <button
                  onClick={() => setShowLogs(false)}
                  className="px-5 py-2 bg-slate-800 hover:bg-slate-700 text-white text-[0.7rem] font-mono font-bold uppercase tracking-wider rounded-lg transition-all border border-slate-700"
                >
                  Close Console
                </button>
              </div>
            </Modal>
          )}

          {/* Critical Alerts */}
          <div className="bg-card border border-border rounded-[2rem] p-6 shadow-sm">
            <h4 className="text-[0.65rem] font-black uppercase tracking-[2px] text-text-muted mb-4">Critical Alerts</h4>
            <div className="space-y-3">
              {stats.alerts && stats.alerts.length > 0 ? (
                stats.alerts.map((alert: any, idx: number) => (
                  <div key={idx} className={`flex items-start gap-3 p-3 rounded-xl border ${alert.severity === 'CRITICAL' ? 'bg-rose-500/5 border-rose-500/10' : 'bg-amber-500/5 border-amber-500/10'}`}>
                    {alert.type === 'SYNC_CONFLICT' ? (
                      <AlertTriangle size={16} className="text-rose-500 mt-0.5" />
                    ) : (
                      <HardDrive size={16} className="text-amber-500 mt-0.5" />
                    )}
                    <div>
                      <p className="text-xs font-bold text-text">{alert.title}</p>
                      <p className="text-[0.6rem] text-text-muted mt-1">{alert.message}</p>
                      {alert.type === 'SYNC_CONFLICT' && (
                        <button className="text-[0.6rem] text-rose-500 font-bold uppercase tracking-wider mt-2 hover:underline">Resolve Now</button>
                      )}
                    </div>
                  </div>
                ))
              ) : (
                <p className="text-[0.6rem] text-text-muted italic">No active alerts</p>
              )}
            </div>
          </div>

        </div>
      </div>
    </div>
  );
}
