"use client";

import { useState } from "react";
import { syncDatabase } from "../lib/api";

export default function SystemInfo() {
  const [isSyncing, setIsSyncing] = useState(false);
  const [syncStatus, setSyncStatus] = useState<string | null>(null);
  const [debugInfo, setDebugInfo] = useState<string>("");

  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 techStack = [
    { name: "FastAPI", role: "Backend Engine", desc: "High-performance Python framework for AI orchestration." },
    { name: "Next.js 14", role: "Frontend Framework", desc: "Modern React framework with server-side capabilities." },
    { name: "Tailwind CSS", role: "Design System", desc: "Premium styling with custom glassmorphism effects." },
    { name: "SQLite", role: "Persistence", desc: "Reliable and fast local database for cloud deployments." },
    { name: "Gemini Pro", role: "AI Intelligence", desc: "Advanced LLM for technical and legal analysis." },
    { name: "Nginx", role: "Reverse Proxy", desc: "Production-grade traffic management." },
  ];

  return (
    <div className="space-y-12 animate-in fade-in slide-in-from-bottom-4 duration-700">
      {/* Brand Section */}
      <div className="glass-card rounded-3xl p-12 border border-white/10 text-center relative overflow-hidden">
        <div className="absolute -right-20 -top-20 h-64 w-64 rounded-full bg-purple-500/10 blur-[100px]" />
        <div className="relative z-10">
          <div className="w-20 h-20 premium-gradient rounded-3xl flex items-center justify-center text-white font-black text-3xl mx-auto mb-8 shadow-2xl shadow-purple-500/40">
            REW
          </div>
          <h2 className="text-4xl font-bold text-white mb-4 tracking-tight">About AndesOps AI</h2>
          <p className="text-slate-400 max-w-2xl mx-auto text-lg leading-relaxed mb-8">
            AndesOps AI is a state-of-the-art platform developed by <span className="text-white font-bold italic">REW Agency</span>. 
            Engineered to transform public procurement through agentic intelligence.
          </p>
          
          {/* Rescue Button */}
          <div className="flex flex-col items-center gap-4 mb-12">
            <button
              onClick={handleSync}
              disabled={isSyncing}
              className="px-8 py-4 rounded-2xl premium-gradient text-white font-bold shadow-xl shadow-purple-500/20 active:scale-95 transition-all disabled:opacity-50"
            >
              {isSyncing ? "Initializing..." : "Seed Demo Data (Manual Sync)"}
            </button>
            {syncStatus && <p className="text-xs font-mono text-purple-400">{syncStatus}</p>}
            
            {/* Debug Area */}
            <div className="mt-8 pt-8 border-t border-white/5 w-full">
              <button 
                onClick={testConnection}
                className="text-[10px] font-bold text-slate-500 hover:text-white uppercase tracking-widest transition"
              >
                [ Test API Connection ]
              </button>
              {debugInfo && (
                <div className="mt-4 p-4 rounded-xl bg-black/40 border border-white/5 text-left">
                  <p className="text-[10px] font-mono text-cyan break-all">{debugInfo}</p>
                </div>
              )}
            </div>
            
            <p className="text-[10px] text-slate-500 max-w-xs uppercase tracking-widest">Use this if the dashboard shows 0 items on first load</p>
          </div>

          <div className="flex items-center justify-center gap-6">
            <a href="https://www.rew.cl" target="_blank" className="px-6 py-3 rounded-2xl bg-white/5 border border-white/10 text-sm font-bold text-slate-300 hover:bg-white/10 transition-all">
              Visit rew.cl
            </a>
            <div className="h-6 w-px bg-white/10" />
            <span className="text-xs font-bold uppercase tracking-[0.3em] text-purple-400">Powered by AndesOps</span>
          </div>
        </div>
      </div>

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

      {/* Development 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">
          <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">System Status: Operational</p>
              <p className="text-xs text-slate-500">Version 1.0.4 - Production Environment</p>
            </div>
          </div>
          <div className="text-center md:text-right">
             <p className="text-[10px] font-bold uppercase tracking-widest text-slate-600 mb-1">Developed & Signed by</p>
             <p className="text-sm font-black text-slate-400 tracking-tighter">REW DIGITAL AGENCY CHILE</p>
          </div>
        </div>
      </div>
    </div>
  );
}
