import React, { useState, useEffect } from 'react';
import {
  LayoutDashboard,
  ScrollText,
  ShieldAlert,
  Users,
  Settings,
  Lock,
  Unlock,
  Activity,
  Network,
  Terminal,
  Server,
  Zap,
  Download
} from 'lucide-react';
import { VaultProvider, useVault } from './contexts/VaultContext';
import { LoginV2 } from './components/LoginV2';
import { Register } from './components/Register';

const SidebarItem = ({ icon: Icon, label, active = false }: any) => (
  <div className={`flex items-center space-x-3 px-4 py-3 rounded-lg cursor-pointer transition-all duration-200 group ${active ? 'bg-indigo-600/10 text-indigo-400 border border-indigo-500/20' : 'text-slate-400 hover:bg-slate-800 hover:text-slate-200'}`}>
    <Icon className={`w-5 h-5 ${active ? 'text-indigo-400' : 'text-slate-500 group-hover:text-slate-300'}`} />
    <span className="font-medium text-sm">{label}</span>
  </div>
);

const MetricCard = ({ label, value, unit, icon: Icon, color }: any) => (
  <div className="bg-slate-900/50 border border-slate-800 p-6 rounded-2xl backdrop-blur-sm relative overflow-hidden group">
    <div className={`absolute top-0 right-0 w-24 h-24 -mr-8 -mt-8 opacity-5 transition-all duration-500 group-hover:scale-110 ${color}`}>
      <Icon className="w-full h-full" />
    </div>
    <div className="flex justify-between items-start mb-4">
      <div className="p-2 bg-slate-800 rounded-lg border border-slate-700">
        <Icon className="w-5 h-5 text-slate-300" />
      </div>
    </div>
    <div className="space-y-1">
      <div className="text-slate-400 text-xs font-semibold uppercase tracking-wider">{label}</div>
      <div className="flex items-baseline space-x-1">
        <div className="text-3xl font-bold text-slate-100">{value}</div>
        <div className="text-slate-500 text-sm">{unit}</div>
      </div>
    </div>
  </div>
);

const Dashboard = () => {
  const { isLocked, isAuthenticated, unlock, decrypt } = useVault();
  const [logs, setLogs] = useState<any[]>([]);
  const [telemetry, setTelemetry] = useState({ fps: 0, players: 0 });
  const [authView, setAuthView] = useState<'login' | 'register'>('login');

  // WebSocket effect (must be before early returns for React Hooks rules)
  useEffect(() => {
    if (!isAuthenticated) return; // Skip if not authenticated
    // Connect ALWAYS to see telemetry
    const socket = new WebSocket('ws://localhost:8080/ws?role=dashboard');
    socket.binaryType = 'arraybuffer';
    
    socket.onmessage = async (event) => {
      if (event.data instanceof ArrayBuffer) {
        // Only decrypt if vault is open
        if (!isLocked) {
          try {
            const decrypted = await decrypt(new Uint8Array(event.data));
            setLogs(prev => [JSON.parse(decrypted), ...prev].slice(0, 100));
          } catch (err) {
            console.error("Decryption failed", err);
          }
        }
      } else {
        // Plaintext Telemetry is always readable
        try {
          const data = JSON.parse(event.data);
          if (data.type === 'TELEMETRY') {
            setTelemetry({ fps: data.fps, players: data.players });
          }
        } catch(e) {}
      }
    };

    return () => socket.close();
  }, [isAuthenticated, isLocked, decrypt]);

  // Show auth screen if not authenticated (after all hooks)
  if (!isAuthenticated) {
    if (authView === 'register') {
      return (
        <Register
          onRegisterSuccess={(token, key, communityId, username) => {
            unlock(key, communityId);
          }}
          onSwitchToLogin={() => setAuthView('login')}
        />
      );
    }

    return (
      <LoginV2
        onLoginSuccess={(token, key, communityId, username) => {
          unlock(key, communityId);
        }}
        onSwitchToRegister={() => setAuthView('register')}
      />
    );
  }

  const handleExport = async () => {
    if (logs.length === 0) return;
    const exportData = {
      community_id: "comm-123-abc",
      export_date: new Date().toISOString(),
      logs: logs
    };
    const blob = new Blob([JSON.stringify(exportData, null, 2)], { type: 'application/json' });
    const url = URL.createObjectURL(blob);
    const a = document.createElement('a');
    a.href = url;
    a.download = `arma-cloud-export-${new Date().getTime()}.json`;
    a.click();
    URL.revokeObjectURL(url);
  };

  return (
    <div className="flex h-screen bg-[#0a0b10] text-slate-200 selection:bg-indigo-500/30">
      {/* Sidebar */}
      <aside className="w-72 border-r border-slate-800 flex flex-col p-6 bg-[#0c0d14]">
        <div className="flex items-center space-x-3 px-2 mb-12">
          <div className="relative">
            <div className="w-9 h-9 bg-indigo-600 rounded-xl flex items-center justify-center">
              <Zap className="w-5 h-5 text-white fill-white" />
            </div>
            <div className="absolute -bottom-1 -right-1 w-3 h-3 bg-green-500 border-2 border-[#0c0d14] rounded-full"></div>
          </div>
          <div className="flex flex-col">
            <span className="text-lg font-bold text-white tracking-tight leading-none">ArmaAdmin</span>
            <span className="text-[10px] text-slate-500 font-bold uppercase tracking-widest mt-1">Enterprise</span>
          </div>
        </div>
        
        <nav className="flex-1 space-y-1">
          <SidebarItem icon={LayoutDashboard} label="Global Overview" active />
          <SidebarItem icon={Terminal} label="Live Console" />
          <SidebarItem icon={ShieldAlert} label="Security Policies" />
          <SidebarItem icon={Users} label="Entity Management" />
          <SidebarItem icon={Settings} label="System Config" />
        </nav>

        <div className="mt-auto space-y-4">
          <div className={`p-4 rounded-2xl border transition-all duration-300 ${isLocked ? 'bg-amber-500/5 border-amber-500/20' : 'bg-indigo-500/5 border-indigo-500/20'}`}>
            <div className="flex items-center justify-between mb-3">
              <span className="text-[10px] font-black uppercase tracking-tighter text-slate-500">Security Layer</span>
              {isLocked ? <Lock className="w-3 h-3 text-amber-500" /> : <Unlock className="w-3 h-3 text-indigo-500" />}
            </div>
            <div className={`text-sm font-bold ${isLocked ? 'text-amber-200' : 'text-indigo-200'}`}>
              {isLocked ? 'Vault Encrypted' : 'Zero-Knowledge Active'}
            </div>
            <div className="text-[10px] text-slate-500 mt-1">E2EE Stream Protection</div>
          </div>
        </div>
      </aside>

      {/* Main View */}
      <main className="flex-1 overflow-y-auto flex flex-col">
        <header className="h-20 border-b border-slate-800 flex items-center justify-between px-10 bg-[#0a0b10]/80 backdrop-blur-md sticky top-0 z-10">
          <div className="flex items-center space-x-2 text-sm">
            <span className="text-slate-500">Infrastructure</span>
            <span className="text-slate-700">/</span>
            <span className="text-slate-200 font-medium">Server Alpha</span>
          </div>

          <div className="flex items-center space-x-6">
            {!isLocked && (
              <>
                <button 
                  onClick={handleExport}
                  className="flex items-center space-x-2 px-4 py-2 bg-slate-800 hover:bg-slate-700 border border-slate-700 rounded-xl text-xs font-bold text-slate-300 transition-colors"
                >
                  <Download className="w-4 h-4" />
                  <span>DSGVO Export</span>
                </button>

                <div className="flex items-center space-x-4 px-4 py-2 bg-slate-900 border border-slate-800 rounded-xl">
                  <div className="flex flex-col items-end">
                    <span className="text-[10px] text-slate-500 font-bold uppercase">Admin Session</span>
                    <span className="text-xs text-slate-300 font-medium">SebastianU</span>
                  </div>
                  <div className="w-8 h-8 rounded-lg bg-indigo-500/20 border border-indigo-500/30 flex items-center justify-center text-indigo-400 font-bold text-xs">
                    SU
                  </div>
                </div>
              </>
            )}
          </div>
        </header>

        <div className="p-10 space-y-10">
          {/* Metrics Grid ALWAYS visible */}
          <div className="grid grid-cols-1 md:grid-cols-4 gap-6">
            <MetricCard label="Simulation Rate" value={telemetry.fps.toFixed(1)} unit="FPS" icon={Activity} color="text-green-500" />
            <MetricCard label="Client Population" value={telemetry.players} unit="/ 64" icon={Users} color="text-indigo-500" />
            <MetricCard label="Inbound Traffic" value="0.8" unit="Gbps" icon={Network} color="text-blue-500" />
            <MetricCard label="Host Latency" value="12" unit="ms" icon={Server} color="text-amber-500" />
          </div>

          {isLocked ? (
            <div className="flex flex-col items-center justify-center py-20 text-center">
              <div className="relative mb-8">
                <div className="absolute inset-0 bg-indigo-600 blur-3xl opacity-20 animate-pulse"></div>
                <div className="relative w-24 h-24 bg-slate-900 border border-slate-800 rounded-3xl flex items-center justify-center">
                  <Lock className="w-10 h-10 text-slate-600" />
                </div>
              </div>
              <h3 className="text-2xl font-bold text-white mb-2 underline decoration-indigo-500/50 decoration-4 underline-offset-8">Encrypted Environment</h3>
              <p className="text-slate-500 max-w-md mt-4 text-sm leading-relaxed">
                The local encryption key is missing. Private metadata, logs, and sensitive data streams are currently inaccessible to the provider.
              </p>
            </div>
          ) : (
            <div className="bg-[#0c0d14] border border-slate-800 rounded-3xl overflow-hidden shadow-2xl">
              <div className="px-8 py-6 border-b border-slate-800 flex justify-between items-center bg-slate-900/30">
                <div className="flex items-center space-x-3">
                  <div className="w-2 h-2 bg-indigo-500 rounded-full animate-ping"></div>
                  <h3 className="font-bold text-slate-100">Zero-Knowledge Stream</h3>
                </div>
                <div className="flex items-center space-x-2">
                  <span className="text-[10px] font-bold text-indigo-400 bg-indigo-400/10 px-3 py-1 rounded-full border border-indigo-400/20">LIVE_E2EE</span>
                </div>
              </div>
              
              <div className="overflow-x-auto">
                <table className="w-full text-left">
                  <thead>
                    <tr className="bg-slate-900/50 text-slate-500 text-[10px] font-black uppercase tracking-widest border-b border-slate-800">
                      <th className="px-8 py-4">Event Tag</th>
                      <th className="px-8 py-4">Descriptor</th>
                      <th className="px-8 py-4 text-right">Node ID</th>
                    </tr>
                  </thead>
                  <tbody className="text-sm font-mono">
                    {logs.map((log, i) => (
                      <tr key={i} className="border-b border-slate-800/50 hover:bg-slate-800/20 transition-colors group">
                        <td className="px-8 py-4 whitespace-nowrap">
                          <span className={`px-2.5 py-1 rounded-md text-[10px] font-bold border ${
                            log.Type === 'CHAT' ? 'bg-blue-500/5 text-blue-400 border-blue-500/20' : 
                            log.Type === 'JOIN' ? 'bg-emerald-500/5 text-emerald-400 border-emerald-500/20' : 
                            log.Type === 'LEAVE' ? 'bg-rose-500/5 text-rose-400 border-rose-500/20' :
                            'bg-slate-800 text-slate-400 border-slate-700'
                          }`}>
                            {log.Type}
                          </span>
                        </td>
                        <td className="px-8 py-4 text-slate-300 font-medium">
                          {log.Content}
                        </td>
                        <td className="px-8 py-4 text-right text-slate-600 group-hover:text-slate-400 transition-colors">
                          AMS-01
                        </td>
                      </tr>
                    ))}
                  </tbody>
                </table>
              </div>
            </div>
          )}
        </div>
      </main>
    </div>
  );
};

function App() {
  return (
    <VaultProvider>
      <Dashboard />
    </VaultProvider>
  );
}

export default App;
