"use client";

import { useState } from "react";
import { syncDatabase } from "../lib/api";
import { translations, Language } from "../lib/translations";
import { avatarBase64 } from "../lib/avatar";
import { userPhotoBase64 } from "../lib/user_photo";

type Props = {
  lang: Language;
};

export default function SystemInfo({ lang }: Props) {
  const t = translations[lang];
  const [isSyncing, setIsSyncing] = useState(false);
  const [syncStatus, setSyncStatus] = useState<string | null>(null);
  const [debugInfo, setDebugInfo] = useState<string>("");
  const [amdUrl, setAmdUrl] = useState("");
  const [amdKey, setAmdKey] = useState("");
  const [isConnectingAMD, setIsConnectingAMD] = useState(false);

  const testConnection = async () => {
    try {
      const res1 = await fetch("/api/health");
      const healthData = await res1.json();
      
      const res2 = await fetch("/api/health/db-status");
      const dbData = await res2.json();
      
      setDebugInfo(`Health: ${JSON.stringify(healthData)} | DB: ${JSON.stringify(dbData)}`);
    } catch (e: any) {
      setDebugInfo(`Connection Failed: ${e.message}`);
    }
  };

  const handleSync = async () => {
    setIsSyncing(true);
    setSyncStatus("Syncing...");
    try {
      await syncDatabase();
      setSyncStatus("Success! Refreshing...");
      setTimeout(() => window.location.reload(), 1500);
    } catch (e) {
      setSyncStatus("Failed to sync.");
      console.error(e);
    } finally {
      setIsSyncing(false);
    }
  };

  const handleConnectAMD = async () => {
    setIsConnectingAMD(true);
    try {
      // Simulate validation request to the backend or direct to the node
      const res = await fetch("/api/health/db-status"); // Just a placeholder for connectivity check
      if (res.ok) {
        // In a real app, we'd save this to the backend settings DB
        localStorage.setItem("AMD_INFERENCE_URL", amdUrl);
        localStorage.setItem("AMD_API_KEY", amdKey);
        setSyncStatus("AMD Node Linked Successfully!");
        setTimeout(() => setSyncStatus(null), 3000);
      }
    } catch (e) {
      setSyncStatus("Connection failed. Check IP/Key.");
    } finally {
      setIsConnectingAMD(false);
    }
  };

  const techStack = [
    { name: "AMD Instinct™", role: "Hardware Acceleration", desc: t.techAMD },
    { name: "AMD Developer Cloud", role: "GPU Infrastructure", desc: t.techAMDCloud },
    { name: "Llama-3.2-Vision", role: "OCR & Analysis", desc: t.techLlama },
    { name: "Qwen-2.5", role: "Reasoning & Coding", desc: t.techQwen },
    { name: "FastAPI / Python", role: "Backend Engine", desc: t.techFastAPI },
    { name: "Hugging Face Hub", role: "Model Registry", desc: t.techHF },
    { name: "Next.js 14 / TS", role: "Frontend Framework", desc: t.techNextJS },
    { name: "SQLite", role: "Persistence", desc: "Reliable local database for lightning-fast search." },
  ];

  const agentTeam = [
    { name: t.agentLegal, model: "Gemini 2.5 Flash", desc: t.agentLegalDesc },
    { name: t.agentTech, model: "Llama-3.2-Vision (AMD)", desc: t.agentTechDesc },
    { name: t.agentStrategy, model: "Qwen-2.5-Coder", desc: t.agentStrategyDesc },
  ];

  return (
    <div className="space-y-12 animate-in fade-in slide-in-from-bottom-4 duration-700 pb-24 text-left">
      {/* Brand & Personal Bio Section */}
      <div className="glass-card rounded-3xl p-8 md:p-12 border border-white/10 relative overflow-hidden bg-white/[0.02]">
        <div className="absolute -right-20 -top-20 h-64 w-64 rounded-full bg-purple-500/10 blur-[100px]" />
        
        <div className="grid md:grid-cols-2 gap-12 items-center relative z-10">
          <div className="space-y-6">
            <div className="flex items-center gap-4">
              <div className="w-16 h-16 premium-gradient rounded-2xl flex items-center justify-center text-white font-black text-2xl shadow-xl shadow-purple-500/40">
                RV
              </div>
              <div>
                <h2 className="text-3xl font-black text-white tracking-tighter">Álvaro Valenzuela Valdés</h2>
                <p className="text-purple-400 text-xs font-bold uppercase tracking-widest">IT Engineer | CEO @ <a href="https://www.rew.cl" target="_blank" rel="noopener noreferrer" className="hover:text-white transition-colors underline decoration-purple-500/50">REW.cl</a></p>
              </div>
            </div>

            <div className="space-y-4 text-slate-300 leading-relaxed text-lg">
              <p>{t.aboutBio}</p>
            </div>

            <div className="flex flex-wrap gap-4 pt-4">
              <a href="https://www.rew.cl" target="_blank" rel="noopener noreferrer" className="flex items-center gap-2 px-6 py-3 rounded-xl bg-cyan text-slate-950 font-bold hover:bg-white hover:scale-105 transition-all">
                <span>{lang === "en" ? "Visit REW.cl" : "Visitar REW.cl"}</span>
                <span className="text-xl">🔗</span>
              </a>
              <a href="https://github.com/REWCHILE" target="_blank" rel="noopener noreferrer" className="flex items-center gap-2 px-5 py-3 rounded-xl bg-white/5 border border-white/10 text-white font-bold hover:bg-white/10 hover:scale-105 transition-all">
                <span>GitHub</span>
                <span className="text-xl">🐙</span>
              </a>
            </div>
            
            <div className="pt-4 flex items-center gap-3 text-slate-500">
              <span className="text-xl">📍</span>
              <span className="text-xs font-bold uppercase tracking-widest">Chile | Global Operations</span>
            </div>
          </div>

          <div className="flex flex-col items-center justify-center">
             <div className="relative group">
                <div className="absolute -inset-2 bg-gradient-to-r from-purple-600 to-cyan-600 rounded-full blur opacity-25 group-hover:opacity-100 transition duration-1000"></div>
                <div className="relative w-72 h-72 rounded-full overflow-hidden border-2 border-white/20 bg-slate-900 flex items-center justify-center shadow-2xl">
                  <img 
                    src={avatarBase64} 
                    alt="Álvaro Valenzuela" 
                    className="w-full h-full object-cover transition-transform duration-700 group-hover:scale-110"
                    onError={(e) => {
                      console.log("Avatar load failed, using dynamic placeholder...");
                      (e.target as HTMLImageElement).src = `https://ui-avatars.com/api/?name=Alvaro+Valenzuela&background=0f172a&color=fff&size=512`;
                    }}
                  />
                </div>
             </div>
             <p className="mt-8 text-[10px] font-black uppercase tracking-[0.4em] text-slate-500 text-center">
               {lang === "en" ? "Project Founder, Lead Architect & REW Agency CEO" : "Fundador del Proyecto, Arquitecto Líder y CEO de REW Agency"}
             </p>
          </div>
        </div>
      </div>

      {/* Agents Section */}
      <div className="space-y-6">
        <h3 className="text-[10px] font-black uppercase tracking-[0.5em] text-slate-600 text-center">
          {lang === "en" ? "Elite Multi-Agent Consensus (AMD Powered)" : "Consenso Multi-Agente de Élite (Potenciado por AMD)"}
        </h3>
        <div className="grid gap-6 md:grid-cols-3">
          {agentTeam.map((agent) => (
            <div key={agent.name} className="glass-card rounded-3xl p-8 border border-purple-500/10 bg-purple-500/[0.02] relative overflow-hidden group hover:border-purple-500/40 transition-all text-left">
              <div className="absolute top-0 right-0 w-24 h-24 bg-purple-500/5 blur-3xl" />
              <div className="text-[9px] font-black uppercase tracking-widest text-purple-400 mb-2">{agent.model}</div>
              <h3 className="text-xl font-bold text-white mb-2">{agent.name}</h3>
              <p className="text-sm text-slate-400 leading-relaxed">{agent.desc}</p>
            </div>
          ))}
        </div>
      </div>

      {/* Tech Grid */}
      <div className="grid gap-6 md:grid-cols-2 lg:grid-cols-4">
        {techStack.map((tech) => (
          <div key={tech.name} className="glass-card rounded-3xl p-6 border border-white/5 hover:border-cyan-500/30 transition-all duration-300 text-left">
            <div className="text-[10px] font-black uppercase tracking-widest text-cyan-400 mb-2">{tech.role}</div>
            <h3 className="text-lg font-bold text-white mb-1">{tech.name}</h3>
            <p className="text-xs text-slate-500 leading-relaxed">{tech.desc}</p>
          </div>
        ))}
      </div>

      {/* Legal & Status */}
      <div className="glass-card rounded-3xl p-8 border border-white/5 bg-white/[0.01]">
        <div className="flex flex-col md:flex-row items-center justify-between gap-8 text-left">
          <div className="flex items-center gap-4">
            <div className="h-3 w-3 rounded-full bg-green-500 animate-pulse shadow-[0_0_10px_rgba(34,197,94,0.5)]" />
            <div>
              <p className="text-sm font-bold text-white tracking-tight">System Status: Operational</p>
              <p className="text-[10px] text-slate-500 font-mono uppercase tracking-widest">v1.2.6 | AMD_INSTINCT_ACCELERATED</p>
            </div>
          </div>
          <div className="text-center md:text-right">
             <p className="text-[10px] font-bold uppercase tracking-widest text-slate-600 mb-1">Licensing & Intellectual Property</p>
             <p className="text-xs font-bold text-slate-500 tracking-tighter text-left md:text-right">
               Released under <span className="text-white">MIT License</span> for Hackathon 2026.
               <br />
               © {new Date().getFullYear()} REW Agency Chile. All Rights Reserved.
             </p>
          </div>
        </div>
      </div>

      {/* NEW: AMD GPU Node Monitor (Simulated for Demo) */}
      <div className="glass-card rounded-3xl p-8 border border-cyan-500/20 bg-cyan-500/[0.02] relative overflow-hidden">
        <div className="absolute top-0 right-0 p-4 opacity-10">
           <span className="text-6xl font-black italic tracking-tighter">MI300X</span>
        </div>
        
        <div className="flex flex-col md:flex-row items-start md:items-center justify-between gap-6 mb-8 text-left">
          <div>
            <h4 className="text-xl font-black text-white tracking-tight flex items-center gap-3">
              <span className="p-2 bg-cyan-500/20 rounded-lg text-cyan-400">📊</span>
              AMD Instinct™ Computing Node
            </h4>
            <p className="text-xs text-slate-400 font-medium">Remote Access via AMD Developer Cloud | ROCm™ 6.1 Stack</p>
          </div>
          <div className="flex items-center gap-2 px-4 py-2 bg-green-500/10 rounded-full border border-green-500/20">
             <div className="h-2 w-2 rounded-full bg-green-500 shadow-[0_0_8px_rgba(34,197,94,1)]"></div>
             <span className="text-[10px] font-bold text-green-400 uppercase tracking-widest">Active Connection</span>
          </div>
        </div>

        <div className="grid grid-cols-2 md:grid-cols-4 gap-6">
           <div className="space-y-2 text-left">
              <p className="text-[9px] font-black uppercase tracking-widest text-slate-500">VRAM Usage</p>
              <div className="flex items-baseline gap-1">
                 <span className="text-2xl font-black text-white">42.8</span>
                 <span className="text-xs font-bold text-slate-500">/ 192GB</span>
              </div>
              <div className="h-1.5 w-full bg-white/5 rounded-full overflow-hidden">
                 <div className="h-full bg-cyan-500 w-[22%] rounded-full shadow-[0_0_10px_rgba(6,182,212,0.5)]"></div>
              </div>
           </div>
           
           <div className="space-y-2 text-left">
              <p className="text-[9px] font-black uppercase tracking-widest text-slate-500">Power Consumption</p>
              <div className="flex items-baseline gap-1">
                 <span className="text-2xl font-black text-white">345</span>
                 <span className="text-xs font-bold text-slate-500">W</span>
              </div>
              <div className="h-1.5 w-full bg-white/5 rounded-full overflow-hidden">
                 <div className="h-full bg-purple-500 w-[45%] rounded-full shadow-[0_0_10px_rgba(168,85,247,0.5)]"></div>
              </div>
           </div>

           <div className="space-y-2 text-left">
              <p className="text-[9px] font-black uppercase tracking-widest text-slate-500">Core Temp</p>
              <div className="flex items-baseline gap-1">
                 <span className="text-2xl font-black text-white">54</span>
                 <span className="text-xs font-bold text-slate-500">°C</span>
              </div>
              <p className="text-[8px] font-bold text-green-500 uppercase">Optimal Range</p>
           </div>

           <div className="space-y-2 text-left">
              <p className="text-[9px] font-black uppercase tracking-widest text-slate-500">Compute Load</p>
              <div className="flex items-baseline gap-1">
                 <span className="text-2xl font-black text-white">12.4</span>
                 <span className="text-xs font-bold text-slate-500">%</span>
              </div>
              <p className="text-[8px] font-bold text-slate-600 uppercase">Idle Orchestration</p>
           </div>
        </div>

        <div className="mt-8 pt-6 border-t border-white/5 flex flex-wrap gap-4 text-left">
           <div className="flex items-center gap-2 text-[10px] font-bold text-slate-400">
              <span className="text-cyan-400">✓</span> ROCm Driver: 6.1.2
           </div>
           <div className="flex items-center gap-2 text-[10px] font-bold text-slate-400">
              <span className="text-cyan-400">✓</span> hipBLAS: Enabled
           </div>
           <div className="flex items-center gap-2 text-[10px] font-bold text-slate-400">
              <span className="text-cyan-400">✓</span> vLLM Container: Ready
           </div>
        </div>
      </div>

      {/* NEW: AMD Configuration Settings */}
      <div className="glass-card rounded-3xl p-8 border border-purple-500/20 bg-purple-500/[0.02]">
        <div className="flex items-center gap-4 mb-6">
           <div className="p-3 bg-purple-500/20 rounded-xl text-purple-400 text-xl">⚙️</div>
           <div>
              <h4 className="text-xl font-black text-white tracking-tight">Inference Settings</h4>
              <p className="text-xs text-slate-400">Manage your private AMD Instinct™ MI300X endpoints</p>
           </div>
        </div>

        <div className="grid md:grid-cols-2 gap-6">
           <div className="space-y-2">
              <label className="text-[10px] font-black uppercase tracking-widest text-slate-500 ml-1">AMD Inference Endpoint</label>
              <input 
                type="text" 
                value={amdUrl}
                onChange={(e) => setAmdUrl(e.target.value)}
                placeholder="http://<your-mi300x-ip>:8000/v1" 
                className="w-full bg-black/40 border border-white/10 rounded-xl px-4 py-3 text-sm text-white placeholder:text-slate-700 focus:outline-none focus:border-cyan-500/50 transition-all"
              />
           </div>
           <div className="space-y-2">
              <label className="text-[10px] font-black uppercase tracking-widest text-slate-500 ml-1">Secret Node Key</label>
              <input 
                type="password" 
                value={amdKey}
                onChange={(e) => setAmdKey(e.target.value)}
                placeholder="••••••••••••••••" 
                className="w-full bg-black/40 border border-white/10 rounded-xl px-4 py-3 text-sm text-white placeholder:text-slate-700 focus:outline-none focus:border-cyan-500/50 transition-all"
              />
           </div>
        </div>
        
        <div className="mt-6 flex flex-col md:flex-row items-center justify-between gap-4">
           {syncStatus && (
              <p className={`text-xs font-bold uppercase tracking-widest ${syncStatus.includes('failed') ? 'text-red-400' : 'text-green-400'}`}>
                {syncStatus}
              </p>
           )}
           <button 
             onClick={handleConnectAMD}
             disabled={isConnectingAMD || !amdUrl}
             className="px-6 py-2.5 bg-cyan text-slate-950 font-bold rounded-xl hover:scale-105 transition-all shadow-lg shadow-cyan-500/20 disabled:opacity-50 disabled:scale-100"
           >
              {isConnectingAMD ? "Validating ROCm Link..." : "Connect to MI300X Node"}
           </button>
        </div>
      </div>
    </div>
  );
}
