import React, { useState, useEffect, useCallback } from 'react';
import { HashRouter, Routes, Route, Link, useLocation, Navigate, useNavigate } from 'react-router-dom';
import { 
  Bell, LogOut, Activity, ChevronRight, Cpu, Settings as SettingsIcon, Terminal, Loader2, Key,
  ShieldCheck, Zap, ArrowRight, ShieldAlert, Globe, Lock, Database, Shield, ZapOff, Fingerprint, Code
} from 'lucide-react';
import { routes } from './views/routes';
import Login from './views/Login';
import Landing from './views/Landing';
import PrivacyPolicy from './views/PrivacyPolicy';
import Documentation from './views/Documentation';
import Airdrop from './views/Airdrop';
import { apiClient } from './services/api';
import { UserSession } from './types/index';

const SidebarItem: React.FC<{ icon: any, label: string, path: string, active: boolean }> = ({ icon: Icon, label, path, active }) => (
  <Link 
    to={path} 
    className={`flex items-center justify-between px-6 py-4 rounded-2xl transition-all duration-500 group ${
      active 
        ? 'bg-white text-black shadow-2xl scale-[1.02]' 
        : 'text-zinc-500 hover:text-white hover:bg-zinc-900/50'
    }`}
  >
    <div className="flex items-center space-x-4">
      <Icon size={18} className={`${active ? 'text-black' : 'text-zinc-600 group-hover:text-blue-500'} transition-colors duration-500`} />
      <span className="font-black text-[10px] uppercase tracking-[0.2em]">{label}</span>
    </div>
    {active && <ChevronRight size={14} />}
  </Link>
);

const Header = ({ user, onLogout }: { user: UserSession, onLogout: () => void }) => {
  const location = useLocation();
  const currentRoute = routes.find(r => r.path === location.pathname);
  const [typedTitle, setTypedTitle] = useState('');

  useEffect(() => {
    if (!currentRoute) return;
    let i = 0;
    const fullText = currentRoute.label;
    setTypedTitle('');
    const timer = setInterval(() => {
      setTypedTitle(fullText.substring(0, i + 1));
      i++;
      if (i >= fullText.length) clearInterval(timer);
    }, 40);
    return () => clearInterval(timer);
  }, [location.pathname, currentRoute]);

  return (
    <header className="h-24 flex items-center justify-between px-10 bg-transparent relative z-50">
      <div className="flex items-center space-x-6">
        <div className="hidden md:flex flex-col">
          <h1 className="text-xl font-black tracking-tighter text-white italic leading-none uppercase">
            {typedTitle || 'CORE'} <span className="text-blue-500 not-italic">NODE</span>
          </h1>
          <p className="text-[10px] text-zinc-600 font-black uppercase tracking-[0.3em] mt-1 flex items-center gap-2">
            <Terminal size={10} />
            ROOT_IDENTIFIER: {user.name.toUpperCase()}
          </p>
        </div>
      </div>

      <div className="flex items-center space-x-8">
        <div className="flex items-center space-x-6">
          <button className="p-3 text-zinc-500 hover:text-white transition-all bg-zinc-950 rounded-xl border border-zinc-900 shadow-xl">
            <Bell size={18} />
          </button>
          <div className="h-8 w-px bg-zinc-900"></div>
          <div className="flex items-center space-x-4 group cursor-pointer" onClick={onLogout}>
            <div className="text-right">
              <p className="text-xs font-black text-white uppercase italic tracking-tighter">{user.name}</p>
              <p className="text-[9px] text-zinc-600 uppercase tracking-[0.2em] font-bold">{user.role}</p>
            </div>
            <div className="w-12 h-12 rounded-2xl bg-zinc-950 border border-zinc-900 flex items-center justify-center group-hover:border-rose-500/50 transition-all shadow-2xl">
              <LogOut size={18} className="text-zinc-600 group-hover:text-rose-500 transition-colors" />
            </div>
          </div>
        </div>
      </div>
    </header>
  );
};

const PrivateTerminal = ({ user, onLogout }: { user: UserSession, onLogout: () => void }) => {
  const location = useLocation();
  const navigate = useNavigate();

  const handleTerminate = async () => {
    await onLogout();
    navigate('/');
  };

  return (
    <div className="flex min-h-screen bg-[#020202] text-zinc-400 antialiased font-sans">
      <aside className="w-80 fixed h-full bg-[#050505] border-r border-zinc-900 p-8 flex flex-col z-50">
        <div className="mb-14 px-4 flex items-center space-x-4">
          <div className="w-12 h-12 bg-white rounded-2xl flex items-center justify-center shadow-2xl">
            <Cpu size={24} className="text-black" />
          </div>
          <div>
            <h1 className="text-lg font-black italic tracking-tighter text-white uppercase leading-none">
              AIBanking <span className="text-blue-500 not-italic">Core</span>
            </h1>
            <p className="text-[9px] uppercase tracking-[0.4em] font-bold text-zinc-600 mt-1">Institutional Mesh</p>
          </div>
        </div>
        
        <nav className="flex-1 space-y-2 overflow-y-auto custom-scrollbar pr-2 pb-10">
          <NavigationLinks />
        </nav>

        <div className="mt-auto pt-10 border-t border-zinc-900 space-y-4">
          <button 
            onClick={handleTerminate}
            className="w-full flex items-center gap-4 px-6 py-4 rounded-2xl text-rose-500 hover:bg-rose-500/10 transition-all font-black text-[10px] uppercase tracking-widest border border-transparent hover:border-rose-500/20"
          >
            <ShieldAlert size={16} />
            <span>Terminate Link</span>
          </button>
          <div className="mt-8 p-6 bg-zinc-950 border border-zinc-900 rounded-[2rem] flex items-center justify-between shadow-2xl">
            <div className="flex items-center gap-3">
              <Activity size={16} className="text-emerald-500" />
              <span className="text-[9px] font-black uppercase tracking-widest text-zinc-500">Node Sync: 100%</span>
            </div>
            <div className="w-2 h-2 bg-emerald-500 rounded-full animate-pulse shadow-[0_0_8px_#10b981]"></div>
          </div>
        </div>
      </aside>

      <main className="flex-1 ml-80 min-h-screen flex flex-col relative z-10">
        <Header user={user} onLogout={onLogout} />
        <div className="px-10 pb-20">
          <Routes>
            {routes.map((route) => (
              <Route key={route.path} path={route.path} element={<route.component />} />
            ))}
            <Route path="*" element={<Navigate to="/overview" replace />} />
          </Routes>
        </div>
      </main>
    </div>
  );
};

const NavigationLinks = () => {
  const location = useLocation();
  const categories = ['core', 'registry', 'finance', 'intelligence', 'system', 'admin'];
  return (
    <div className="space-y-10">
      {categories.map(cat => {
        const catRoutes = routes.filter(r => r.showInSidebar && r.category === cat);
        if (catRoutes.length === 0) return null;
        return (
          <div key={cat} className="space-y-3">
             <p className="px-6 text-[8px] font-black uppercase text-zinc-700 tracking-[0.5em] mb-4">{cat.toUpperCase()}_SUITE</p>
             {catRoutes.map((route) => (
              <SidebarItem 
                key={route.path} 
                icon={route.icon} 
                label={route.label} 
                path={route.path} 
                active={location.pathname === route.path} 
              />
            ))}
          </div>
        );
      })}
    </div>
  );
};

const NeuralGate = ({ onAuthorized }: { onAuthorized: (tier: 'enterprise' | 'regular') => void }) => {
  const [loading, setLoading] = useState(false);

  const handleEnterpriseLink = async () => {
    setLoading(true);
    try {
      await window.aistudio.openSelectKey();
      onAuthorized('enterprise');
    } catch (e) {
      console.error("Enterprise gate refusal.");
    } finally {
      setLoading(false);
    }
  };

  const handleRegularLink = () => {
    onAuthorized('regular');
  };

  return (
    <div className="min-h-screen bg-black flex flex-col items-center justify-center p-12 relative overflow-hidden">
      <div className="absolute inset-0 z-0 opacity-20">
        <div className="absolute top-0 left-0 w-full h-full bg-[radial-gradient(circle_at_50%_50%,_#1e1b4b_0%,_transparent_70%)]"></div>
        <div className="absolute inset-0 bg-[linear-gradient(to_right,#80808012_1px,transparent_1px),linear-gradient(to_bottom,#80808012_1px,transparent_1px)] bg-[size:80px_80px]"></div>
      </div>

      <div className="max-w-4xl w-full relative z-10 text-center space-y-16">
        <div className="relative inline-block group">
          <div className="absolute -inset-8 bg-blue-600/20 blur-3xl rounded-full opacity-50 group-hover:opacity-100 transition-opacity"></div>
          <div className="w-32 h-32 bg-white rounded-[3.5rem] flex items-center justify-center mx-auto shadow-[0_40px_80px_rgba(255,255,255,0.1)] group-hover:rotate-12 transition-transform duration-1000 border-4 border-zinc-900">
            <Lock size={64} className="text-black" />
          </div>
        </div>
        
        <div className="space-y-8">
          <h1 className="text-7xl lg:text-8xl font-black italic text-white uppercase tracking-tighter leading-none">
            Neural <span className="text-blue-500 not-italic">Gateway</span>
          </h1>
          <p className="text-zinc-500 font-bold text-2xl leading-relaxed italic max-w-2xl mx-auto">
            "To initialize the aibanking.dev ledger, establishing a secure neural link is mandatory. Select your protocol tier."
          </p>
        </div>
        
        <div className="grid grid-cols-1 md:grid-cols-2 gap-8 max-w-3xl mx-auto">
          <button 
            onClick={handleEnterpriseLink}
            disabled={loading}
            className="flex flex-col items-center gap-6 py-10 px-8 bg-blue-600 hover:bg-blue-500 text-white rounded-[3.5rem] transition-all shadow-[0_30px_60px_rgba(37,99,235,0.4)] group active:scale-95 border-2 border-transparent hover:border-white/20"
          >
            <Zap size={40} className="group-hover:scale-125 transition-transform" />
            <div className="text-center">
              <span className="block font-black text-sm uppercase tracking-[0.4em] mb-2">Enterprise Tier</span>
              <span className="block text-[10px] font-bold text-blue-100 uppercase tracking-widest opacity-60 italic">Requires Paid Google API Node</span>
            </div>
            <ArrowRight size={24} className="group-hover:translate-x-4 transition-transform" />
          </button>

          <button 
            onClick={handleRegularLink}
            className="flex flex-col items-center gap-6 py-10 px-8 bg-zinc-900 hover:bg-zinc-800 text-white rounded-[3.5rem] transition-all shadow-2xl group active:scale-95 border-2 border-zinc-800 hover:border-zinc-700"
          >
            <Globe size={40} className="text-zinc-600 group-hover:text-blue-400 group-hover:scale-125 transition-all" />
            <div className="text-center">
              <span className="block font-black text-sm uppercase tracking-[0.4em] mb-2">Regular Tier</span>
              <span className="block text-[10px] font-bold text-zinc-500 uppercase tracking-widest opacity-60 italic">Free Local Instance Access</span>
            </div>
            <ArrowRight size={24} className="text-zinc-700 group-hover:text-zinc-500 group-hover:translate-x-4 transition-all" />
          </button>
        </div>

        <div className="pt-12 border-t border-zinc-900 space-y-6">
          <div className="flex flex-col md:flex-row items-center justify-center gap-10">
            <a href="https://ai.google.dev/gemini-api/docs/billing" target="_blank" rel="noreferrer" className="text-[10px] font-black text-zinc-600 hover:text-white uppercase tracking-widest transition-colors flex items-center gap-2">
              <Key size={12} /> Registry Documentation
            </a>
            <p className="text-[10px] font-black text-zinc-700 uppercase tracking-[0.4em]">v6.5.0 Institutional Registry • Secured via RSA-OAEP</p>
          </div>
          <div className="flex justify-center gap-12 opacity-20">
            <ShieldCheck size={32} /><Globe size={32} /><Database size={32} />
          </div>
        </div>
      </div>
    </div>
  );
};

const App: React.FC = () => {
  const [hasKey, setHasKey] = useState<boolean | null>(null);
  const [tier, setTier] = useState<'enterprise' | 'regular' | null>(null);
  const [currentUser, setCurrentUser] = useState<UserSession | null>(null);
  const [isAuthChecked, setIsAuthChecked] = useState<boolean>(false);

  const checkStatus = useCallback(async () => {
    const keySelected = await window.aistudio.hasSelectedApiKey();
    setHasKey(keySelected);
    const { user } = await apiClient.auth.me();
    setCurrentUser(user);
    setIsAuthChecked(true);
  }, []);

  useEffect(() => {
    checkStatus();
    window.addEventListener('auth-update', checkStatus);
    return () => window.removeEventListener('auth-update', checkStatus);
  }, [checkStatus]);

  const handleLogout = async () => {
    await apiClient.auth.logout();
    setCurrentUser(null);
  };

  const onAuthorized = (selectedTier: 'enterprise' | 'regular') => {
    setTier(selectedTier);
    if (selectedTier === 'regular') setHasKey(true);
    else checkStatus();
  };

  if (!isAuthChecked || (hasKey === null && !tier)) {
    return (
      <div className="min-h-screen bg-black flex flex-col items-center justify-center space-y-12">
        <div className="relative">
          <div className="w-24 h-24 border-4 border-zinc-900 border-t-blue-500 rounded-full animate-spin"></div>
          <Cpu className="absolute top-1/2 left-1/2 -translate-x-1/2 -translate-y-1/2 text-white" size={32} />
        </div>
        <p className="text-[11px] font-black text-zinc-700 uppercase tracking-[0.8em] animate-pulse italic">Synchronizing Node Registry...</p>
      </div>
    );
  }

  if (!hasKey && tier !== 'regular') {
    return <NeuralGate onAuthorized={onAuthorized} />;
  }

  return (
    <HashRouter>
      <Routes>
        <Route path="/" element={currentUser ? <Navigate to="/overview" replace /> : <Landing />} />
        <Route path="/login" element={currentUser ? <Navigate to="/overview" replace /> : <Login />} />
        <Route path="/airdrop" element={<Airdrop />} />
        <Route path="/manifesto" element={<PrivacyPolicy />} />
        <Route path="/documentation" element={<Documentation />} />
        <Route path="/*" element={currentUser ? (
          <PrivateTerminal user={currentUser} onLogout={handleLogout} />
        ) : (
          <Navigate to="/" replace />
        )} />
      </Routes>
    </HashRouter>
  );
};

export default App;