"use client";

import { useCallback, useEffect, useRef, useState, Suspense } from "react";
import { useSearchParams, useRouter } from "next/navigation";
import { motion, AnimatePresence } from "motion/react";
import { LiveSimulator } from "@/components/LiveSimulator";
import {
  UserCircle,
  List,
  X,
  ChevronDown,
  Settings,
  Check,
  Database,
  Mic,
  Lock,
  Database as DbIcon
} from "lucide-react";
import { generateSystemInstruction } from "@/lib/constants";

const SUPPORTED_VOICES = [
  { id: "Puck", name: "Puck" },
  { id: "Charon", name: "Charon" },
  { id: "Fenrir", name: "Fenrir" },
  { id: "Kore", name: "Kore" },
  { id: "Aoede", name: "Aoede" },
  { id: "Orion", name: "Orion" },
];

function SessionGate() {
  const searchParams = useSearchParams();
  const router = useRouter();
  const token = searchParams.get("token");

  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const [profile, setProfile] = useState<any>(null);
  const [sessionInfo, setSessionInfo] = useState<any>(null);
  const [chapters, setChapters] = useState<any[]>([]);
  const [completedChapters, setCompletedChapters] = useState<string[]>([]);
  
  // UI State from original
  const [isLeftOpen, setIsLeftOpen] = useState(false);
  const [isRightOpen, setIsRightOpen] = useState(false);
  const [voice, setVoice] = useState("Puck");
  const [isVoiceMenuOpen, setIsVoiceMenuOpen] = useState(false);
  const [logoUrl, setLogoUrl] = useState("");
  const [apiKey, setApiKey] = useState("");
  const [liveModel, setLiveModel] = useState("");
  const [secretMessage, setSecretMessage] = useState<string | null>(null);
  const sessionInfoRef = useRef<any>(null);
  useEffect(() => {
    sessionInfoRef.current = sessionInfo;
  }, [sessionInfo]);

  useEffect(() => {
    if (!token) {
      setError("No access token provided.");
      setLoading(false);
      return;
    }
    validateToken();
  }, [token]);

  const validateToken = async () => {
    try {
      const res = await fetch("/api/access-links/validate", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ token })
      });
      const json = await res.json();

      if (json.success && json.data.valid) {
        setProfile(json.data.profile);
        setVoice(json.data.profile.preferredVoice || "Puck");
        // Fetch chapters and settings
        const [chaptersRes, settingsRes] = await Promise.all([
          fetch("/api/curriculum"),
          fetch("/api/settings")
        ]);
        const chaptersJson = await chaptersRes.json();
        const settingsJson = await settingsRes.json();
        
        if (chaptersJson.success) setChapters(chaptersJson.data);
        if (settingsJson.success) {
          setLogoUrl(settingsJson.data.logo_url || "");
        }

        // Fetch secure API key for the session
        const configRes = await fetch("/api/session/config", {
          method: "POST",
          headers: { "Content-Type": "application/json" },
          body: JSON.stringify({ token })
        });
        const configJson = await configRes.json();
        if (configJson.success) {
          setApiKey(configJson.apiKey);
          if (configJson.model) setLiveModel(configJson.model);
        }

        // Check if there are completed chapters for this profile
        // For now we'll start empty or fetch from a new endpoint if we had one
        // But let's just assume we start fresh or fetch from sessions
        setCompletedChapters([]); 
      } else {
        setError(getErrorMessage(json.data.reason, json.data));
      }
    } catch (err) {
      setError("Failed to validate access link. Please try again.");
    } finally {
      setLoading(false);
    }
  };

  const getErrorMessage = (reason: string, data: any) => {
    switch (reason) {
      case "not_found": return "Invalid or unrecognized access link.";
      case "revoked": return "This access link has been revoked by your mentor.";
      case "not_yet_active": return `This link is not active until ${new Date(data.validFrom).toLocaleString()}`;
      case "expired": return "This access link has expired.";
      case "session_limit": return "You have reached the maximum number of sessions for this link.";
      default: return "Access denied.";
    }
  };

  const ensureDbSession = useCallback(async () => {
    if (sessionInfoRef.current) return sessionInfoRef.current;
    if (!profile?.id || !token) return null;
    try {
      const res = await fetch("/api/sessions", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ profileId: profile.id, token }),
      });
      const json = await res.json();
      if (json.success) {
        sessionInfoRef.current = json.data;
        setSessionInfo(json.data);
        return json.data;
      }
      setError("Failed to initialize session database record.");
      return null;
    } catch (err) {
      setError("Connection error while starting session.");
      return null;
    }
  }, [profile?.id, token]);

  const handleChapterComplete = async (id: string) => {
    // 1. Update UI
    setCompletedChapters(prev => [...prev, id]);
    
    // 2. Save to database
    if (sessionInfo) {
      await fetch(`/api/sessions/${sessionInfo.id}/drills`, {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({
          elementId: id,
          score: 100,
          passed: true,
          feedback: "Chapter successfully completed in live session."
        })
      });
    }

    const SECRET_MESSAGES = [
      "Your dedication is your greatest weapon. Keep pushing forward.",
      "Every drill mastered brings you closer to ultimate success.",
      "Mission accomplished: Chapter complete. On to the next objective.",
      "Excellent work, operative. Your capabilities are increasing.",
      "A true professional never stops training. Outstanding results.",
    ];
    setSecretMessage(SECRET_MESSAGES[Math.floor(Math.random() * SECRET_MESSAGES.length)]);
    setTimeout(() => setSecretMessage(null), 10000);
  };

  const handleSessionEnd = async (logs: any[], audioBlob?: Blob) => {
    const current = sessionInfoRef.current;
    if (!current) return;

    const formData = new FormData();
    formData.append("logs", JSON.stringify(logs));
    if (audioBlob) {
      formData.append("audio", audioBlob, "session_audio.webm");
    }

    fetch(`/api/sessions/${current.id}/sync`, {
      method: "POST",
      body: formData,
    }).catch(err => console.error("Session sync failed:", err));

    sessionInfoRef.current = null;
    setSessionInfo(null);
  };

  if (loading) {
    return (
      <div className="h-screen bg-slate-50 flex items-center justify-center font-mono">
        <div className="text-[#044f54] text-center space-y-4">
          <div className="w-12 h-12 border-4 border-[#044f54]/20 border-t-[#044f54] rounded-full animate-spin mx-auto"></div>
          <p className="uppercase tracking-[0.2em] text-xs font-bold">Initializing Secure Connection...</p>
        </div>
      </div>
    );
  }

  if (error) {
    return (
      <div className="h-screen bg-slate-50 flex items-center justify-center p-6 font-sans">
        <div className="bg-white p-10 rounded-xl border border-red-200 shadow-2xl max-w-md w-full text-center">
          <div className="w-20 h-20 bg-red-100 text-red-600 rounded-full flex items-center justify-center mx-auto mb-8 border border-red-200">
            <Lock size={32} />
          </div>
          <h2 className="text-2xl font-bold text-slate-800 mb-4 tracking-tight">Access Restricted</h2>
          <p className="text-slate-500 leading-relaxed mb-8">{error}</p>
          <button 
            onClick={() => router.push("/")}
            className="w-full bg-[#044f54] text-white py-3 rounded-lg font-bold uppercase tracking-widest hover:bg-[#044f54]/90 transition-all"
          >
            Return to Base
          </button>
        </div>
      </div>
    );
  }

  const progressPercent = chapters.length > 0 ? Math.round((completedChapters.length / chapters.length) * 100) : 0;
  const systemInstruction = generateSystemInstruction(chapters, completedChapters);

  return (
    <div className="h-screen bg-slate-50 text-[#044f54] font-sans flex flex-col overflow-hidden select-none">
      {/* Top Header */}
      <header className="relative h-16 border-b border-[#044f54]/10 flex items-center justify-between px-4 sm:px-8 bg-slate-50 shrink-0">
        <div className="flex items-center gap-2 sm:gap-4">
          <button onClick={() => setIsLeftOpen(!isLeftOpen)} className="lg:hidden p-1.5 text-[#044f54]/60 hover:text-[#044f54] hover:bg-[#044f54]/10 rounded-md transition-colors">
            <UserCircle className="w-5 h-5" />
          </button>
          <div className="flex flex-col border-l border-[#044f54]/10 pl-2 sm:pl-4">
            <span className="text-[10px] sm:text-[11px] tracking-[0.15em] text-[#044f54]/90 uppercase font-bold">AGENT 007 RMS</span>
            <span className="text-[8px] sm:text-[9px] text-[#044f54] uppercase font-mono truncate max-w-[120px] sm:max-w-none">
              Session ID: RM-{sessionInfo?.sessionNumber || '0000'}-DELTA
            </span>
          </div>
        </div>

        {logoUrl && (
          <div className="absolute left-1/2 top-1/2 -translate-x-1/2 -translate-y-1/2 pointer-events-none hidden sm:block">
            <img src={logoUrl} alt="Logo" className="h-12 sm:h-16 max-w-[250px] sm:max-w-[300px] object-contain" />
          </div>
        )}

        <div className="flex items-center gap-4 sm:gap-12 font-mono text-[9px] sm:text-[11px] tracking-widest text-[#044f54]/60">
          <div className="relative hidden sm:flex flex-col items-end">
            <span className="text-[#044f54]/30 uppercase">Connection Profile</span>
            <button 
              onClick={() => setIsVoiceMenuOpen(true)}
              className="text-[#044f54] uppercase hover:text-[#044f54]/80 flex items-center gap-1"
            >
              Voice: {voice} <ChevronDown className="w-3 h-3" />
            </button>
          </div>
          <button onClick={() => setIsRightOpen(!isRightOpen)} className="xl:hidden p-1.5 text-[#044f54]/60 hover:text-[#044f54] hover:bg-[#044f54]/10 rounded-md transition-colors">
            <List className="w-5 h-5" />
          </button>
        </div>
      </header>

      <main className="flex-1 flex overflow-hidden relative">
        {isLeftOpen && <div className="absolute inset-0 bg-slate-50/60 z-30 lg:hidden" onClick={() => setIsLeftOpen(false)} />}
        
        {/* Sidebar Left: Candidate Profile */}
        <aside className={`absolute lg:relative inset-y-0 left-0 w-64 border-r border-[#044f54]/10 bg-slate-50 p-6 flex flex-col z-40 transition-transform duration-300 ease-in-out ${isLeftOpen ? "translate-x-0" : "-translate-x-full lg:translate-x-0"}`}>
          <div className="flex justify-between items-center mb-8 lg:block">
            <h2 className="text-[10px] text-[#044f54]/40 uppercase tracking-widest lg:mb-4">Candidate Profile</h2>
            <button onClick={() => setIsLeftOpen(false)} className="lg:hidden text-[#044f54]/40 hover:text-[#044f54]"><X className="w-4 h-4" /></button>
          </div>
          <div className="mb-8">
            <div className="p-4 border border-[#044f54]/10 rounded bg-[#044f54]/[0.02]">
              <div className="text-lg font-light mb-1">{profile?.name || "Agent Trainee"}</div>
              <div className="text-[10px] font-mono text-[#044f54]/80 uppercase">{profile?.role || "RMS Candidate"}</div>
            </div>
          </div>
          <div className="mb-8 hidden sm:block">
            <h2 className="text-[10px] text-[#044f54]/40 uppercase tracking-widest mb-4">Mission Progress</h2>
            <div className="space-y-4">
              <div>
                <div className="flex justify-between text-[11px] mb-1 font-mono"><span>OVERALL</span><span className="text-[#044f54]">{progressPercent}%</span></div>
                <div className="h-1 w-full bg-[#044f54]/5 overflow-hidden rounded-full"><div className="h-full bg-[#044f54]" style={{ width: `${progressPercent}%` }}></div></div>
              </div>
              <div className="grid grid-cols-2 gap-2 text-[10px] font-mono uppercase">
                <div className="p-2 border border-[#044f54]/5 bg-[#044f54]/[0.01] rounded"><div className="text-[#044f54]/40">Status</div><div className="text-lg text-[#044f54]/90">ACTIVE</div></div>
                <div className="p-2 border border-[#044f54]/5 bg-[#044f54]/[0.01] rounded"><div className="text-[#044f54]/40">System</div><div className="text-lg">ONLINE</div></div>
              </div>
            </div>
          </div>
          <div className="mt-auto">
            <div className="p-4 border-l-2 border-[#044f54] bg-[#044f54]/5 rounded-r">
              <p className="text-[11px] italic text-[#044f54]/70">"Success relies on practical skill development, not just theory."</p>
            </div>
          </div>
        </aside>

        {/* Main Content */}
        <section className="flex-1 flex flex-col bg-slate-50 relative w-full h-full min-w-0">
          <div className="absolute inset-0 opacity-[0.03] pointer-events-none" style={{ backgroundImage: "radial-gradient(#fff 1px, transparent 1px)", backgroundSize: "20px 20px" }}></div>
          <div className="flex-1 min-h-0 relative z-10 w-full overflow-y-auto">
            <LiveSimulator
              voice={voice}
              systemInstruction={systemInstruction}
              apiKey={apiKey}
              model={liveModel}
              onSessionStart={ensureDbSession}
              onChapterComplete={handleChapterComplete}
              onSessionEnd={handleSessionEnd}
            />
          </div>
        </section>

        {isRightOpen && <div className="absolute inset-0 bg-slate-50/60 z-30 xl:hidden" onClick={() => setIsRightOpen(false)} />}
        
        {/* Sidebar Right: Chapter Index */}
        <aside className={`absolute xl:relative inset-y-0 right-0 w-80 border-l border-[#044f54]/10 bg-slate-50 p-6 flex flex-col z-40 transition-transform duration-300 ease-in-out ${isRightOpen ? "translate-x-0" : "translate-x-[100%] xl:translate-x-0"}`}>
          <div className="flex justify-between items-center mb-6 xl:block">
            <h2 className="text-[10px] text-[#044f54]/40 uppercase tracking-widest xl:mb-6">Results Maker System Index</h2>
            <button onClick={() => setIsRightOpen(false)} className="xl:hidden text-[#044f54]/40 hover:text-[#044f54]"><X className="w-4 h-4" /></button>
          </div>
          <div className="flex-1 overflow-y-auto space-y-1 pr-2">
            {chapters.map((chapter, i) => (
              <div key={i} className={`flex items-center gap-3 p-2 rounded transition-opacity cursor-default ${completedChapters.includes(chapter.id) ? "opacity-100 bg-[#044f54]/5" : "opacity-30 grayscale hover:opacity-50"}`}>
                {completedChapters.includes(chapter.id) && <Check className="w-3 h-3 text-[#044f54]" />}
                <span className="text-[10px] font-mono">{chapter.id}</span>
                <span className="text-xs font-medium">{chapter.title}</span>
              </div>
            ))}
          </div>
        </aside>
      </main>

      {/* Voice Selection Modal */}
      <AnimatePresence>
        {isVoiceMenuOpen && (
          <motion.div
            initial={{ opacity: 0 }}
            animate={{ opacity: 1 }}
            exit={{ opacity: 0 }}
            transition={{ duration: 0.3 }}
            className="fixed inset-0 z-[100] bg-slate-50/90 backdrop-blur-md flex items-center justify-center p-4 sm:p-8"
          >
            <motion.div
              initial={{ y: 50, opacity: 0 }}
              animate={{ y: 0, opacity: 1 }}
              exit={{ y: 50, opacity: 0 }}
              transition={{ duration: 0.3 }}
              className="w-full max-w-xl bg-slate-50 border border-[#044f54] shadow-[0_0_50px_rgba(4,79,84,0.15)] rounded relative overflow-hidden flex flex-col"
            >
              {/* Scanline overlay */}
              <div className="absolute inset-0 pointer-events-none bg-[repeating-linear-gradient(0deg,transparent,transparent_2px,rgba(4,79,84,0.1)_2px,rgba(4,79,84,0.1)_4px)]"></div>

              {/* Header */}
              <div className="border-b border-[#044f54]/30 bg-[#044f54]/10 p-4 flex justify-between items-center relative z-10">
                <div className="flex items-center gap-3">
                  <div className="w-8 h-8 bg-[#044f54] flex items-center justify-center text-white font-black uppercase text-xs tracking-widest rounded-sm shadow-[0_0_15px_rgba(4,79,84,0.5)]">
                    MI6
                  </div>
                  <div className="flex flex-col">
                    <span className="text-[#044f54] font-bold text-sm tracking-widest uppercase">
                      Operative Database
                    </span>
                    <span className="text-[#044f54]/40 text-[10px] font-mono uppercase tracking-widest">
                      Level 7 Clearance Required
                    </span>
                  </div>
                </div>
                <button
                  onClick={() => setIsVoiceMenuOpen(false)}
                  className="text-[#044f54]/60 hover:text-[#044f54] transition-colors bg-[#044f54]/10 hover:bg-[#044f54]/20 p-1.5 rounded"
                >
                  <X className="w-5 h-5" />
                </button>
              </div>

              {/* Body */}
              <div className="p-6 relative z-10">
                <div className="mb-6 space-y-1">
                  <h3 className="text-[#044f54] text-lg font-serif italic tracking-wider">
                    Select Vocal Profile
                  </h3>
                  <p className="text-[#044f54]/60 text-xs font-mono tracking-widest uppercase">
                    Initialize deep-cover voice modification module.
                  </p>
                </div>

                <div className="grid grid-cols-1 sm:grid-cols-2 gap-3">
                  {SUPPORTED_VOICES.map((v) => (
                    <button
                      key={v.id}
                      onClick={() => {
                        setVoice(v.id);
                        setTimeout(() => setIsVoiceMenuOpen(false), 400); 
                      }}
                      className={`group relative p-4 border flex flex-col text-left transition-all duration-300 ${voice === v.id ? "border-[#044f54] bg-[#044f54]/10 shadow-[0_0_20px_rgba(4,79,84,0.15)]" : "border-[#044f54]/10 hover:border-[#044f54]/50 hover:bg-[#044f54]/5 bg-[#044f54]/[0.02]"}`}
                    >
                      <span className="text-[10px] text-[#044f54]/40 font-mono mb-2">
                        ID: {v.id.toUpperCase()}-00
                        {SUPPORTED_VOICES.findIndex((o) => o.id === v.id) + 1}
                      </span>
                      <div className="flex justify-between items-center">
                        <span
                          className={`font-bold tracking-widest uppercase ${voice === v.id ? "text-[#044f54]" : "text-[#044f54]"}`}
                        >
                          {v.name}
                        </span>
                        {voice === v.id && (
                          <div className="w-2 h-2 bg-[#044f54] rounded-full animate-pulse shadow-[0_0_8px_rgba(4,79,84,1)]"></div>
                        )}
                      </div>
                      <div className="absolute top-0 right-0 p-1 opacity-0 group-hover:opacity-100 transition-opacity">
                        <div className="w-2 h-2 border-t border-r border-[#044f54]"></div>
                      </div>
                      <div className="absolute bottom-0 left-0 p-1 opacity-0 group-hover:opacity-100 transition-opacity">
                        <div className="w-2 h-2 border-b border-l border-[#044f54]"></div>
                      </div>
                    </button>
                  ))}
                </div>

                <div className="mt-8 flex justify-between items-end border-t border-[#044f54]/10 pt-4">
                  <div className="flex gap-2 items-center">
                    <div className="w-2 h-2 bg-[#044f54] rounded-full animate-pulse"></div>
                    <span className="text-[9px] text-[#044f54]/80 font-mono tracking-widest uppercase items-center">
                      Connection Secured
                    </span>
                  </div>
                  <span className="text-[10px] text-[#044f54]/40 font-mono uppercase">
                    RMS / v2.0.4
                  </span>
                </div>
              </div>
            </motion.div>
          </motion.div>
        )}
      </AnimatePresence>

      <AnimatePresence>
        {secretMessage && (
          <motion.div initial={{ opacity: 0, y: 50 }} animate={{ opacity: 1, y: 0 }} exit={{ opacity: 0, y: 50 }} className="fixed bottom-16 right-8 z-50 max-w-sm bg-[#044f54] text-white p-4 rounded shadow-2xl border border-white/20">
            <div className="flex items-center gap-2 border-b border-white/20 pb-2 mb-2">
              <div className="w-2 h-2 bg-red-500 rounded-full animate-pulse"></div>
              <span className="text-[10px] font-mono tracking-widest text-red-300 uppercase font-bold">Encrypted Intel Received</span>
            </div>
            <p className="text-sm italic leading-relaxed font-serif">"{secretMessage}"</p>
          </motion.div>
        )}
      </AnimatePresence>

      <footer className="h-12 border-t border-[#044f54]/10 bg-slate-50 flex items-center px-4 sm:px-8 hidden sm:flex shrink-0">
        <div className="flex gap-4 sm:gap-8">
          <div className="flex items-center gap-2"><div className="w-2 h-2 bg-[#044f54] rounded-full animate-pulse"></div><span className="text-[9px] sm:text-[10px] font-bold uppercase tracking-widest">Always Have FUN</span></div>
          <div className="flex items-center gap-2"><div className="w-2 h-2 bg-[#044f54]/90 rounded-full animate-pulse"></div><span className="text-[9px] sm:text-[10px] font-bold uppercase tracking-widest">You've GOT This</span></div>
          <div className="flex items-center gap-2"><div className="w-2 h-2 bg-[#044f54]/40 rounded-full"></div><span className="text-[9px] sm:text-[10px] font-bold uppercase tracking-widest opacity-40">So What!</span></div>
        </div>
        <div className="ml-auto text-[8px] sm:text-[10px] font-mono text-[#044f54]/20 uppercase tracking-[0.3em]">SECURE PROTOCOL ENABLED // RMS v4.1</div>
      </footer>
    </div>
  );
}

export default function SessionPage() {
  return (
    <Suspense fallback={<div className="h-screen bg-slate-50"></div>}>
      <SessionGate />
    </Suspense>
  );
}
