import { useState, useRef, FormEvent } from 'react';
import { motion } from 'motion/react';
import { WifiOff, Lock } from 'lucide-react';
import { LogSequence } from '../../types';
import { synth } from '../../utils/audioSynth';

interface Slide9OfflineDemoProps {
  showToast: (msg: string) => void;
}

export default function Slide9OfflineDemo({ showToast }: Slide9OfflineDemoProps) {
  const [isDisconnected, setIsDisconnected] = useState<boolean>(false);
  const [demoStep, setDemoStep] = useState<number>(0);
  const [demoLogs, setDemoLogs] = useState<string[]>([]);
  const [demoPrompt, setDemoPrompt] = useState<string>("");
  const [demoResponse, setDemoResponse] = useState<string>("");
  const [demoPending, setDemoPending] = useState<boolean>(false);
  const demoLogTimerRef = useRef<NodeJS.Timeout[]>([]);

  const handleSeverConnection = () => {
    synth.playDisconnect();
    setIsDisconnected(true);
    setDemoStep(1);
    setDemoLogs([]);
    setDemoResponse("");
    setDemoPrompt("");
    
    demoLogTimerRef.current.forEach(t => clearTimeout(t));
    demoLogTimerRef.current = [];

    const logSequence: LogSequence[] = [
      { text: "⚡ [SEVER_INITIATED] Intercepting all global socket calls...", delay: 200 },
      { text: "🔴 [PING_FAILED] api.openai.com - Request timeout (Route blocked)", delay: 800 },
      { text: "🔴 [CONN_DEAD] gateway.anthropic.com - Destination unreachable", delay: 1400 },
      { text: "🔒 [OFFLINE_ENFORCED] Firewall rules securely locked. Outbound data leakage risk: 0.00%", delay: 2000 },
      { text: "📦 [DEPLOYING] Mount local weights: 'llama-3-8b-instruct.Q4_K_M.gguf'", delay: 2600 },
      { text: "🚀 [CPU_AVX2] GPU acceleration mapped to RTX VRAM Core.", delay: 3200 },
      { text: "✅ [Sovereign-Llama3-v1] Online in 100% disconnected sandbox environment.", delay: 3800 }
    ];

    logSequence.forEach((seq) => {
      const timer = setTimeout(() => {
        setDemoLogs((prev) => [...prev, seq.text]);
        synth.playBlip();
        if (seq.text.startsWith('✅')) {
          setDemoStep(2);
        }
      }, seq.delay);
      demoLogTimerRef.current.push(timer);
    });
  };

  const submitDemoPrompt = (e: FormEvent) => {
    e.preventDefault();
    if (!demoPrompt.trim() || demoPending) return;
    synth.playClick();
    setDemoPending(true);
    setDemoResponse("");

    const mockAiResponses: { [key: string]: string } = {
      default: "SYSTEM RESPONSE // SOVEREIGN ENGINE:\n\nInput processed completely on-device in 143ms.\nResult: Secure compliance extraction verified. Ready for download. Zero bits sent beyond localhost.",
      analysts: "LOCAL_ANALYSIS //\nWe ran sentiment scoring on the structured CSV feed. Standard Deviances: \n- Positivity: 84.1%\n- Risk Alert: Trace detected on Cloud API usage. Highly recommend immediate on-site fallback protocol.",
      extract: "EXTRACTED SCHEMA:\n{\n  'transaction_id': 'TX90812',\n  'sovereign_rating': '10.0',\n  'cost_per_token': '$0.000000000'\n}"
    };

    setTimeout(() => {
      const p = demoPrompt.toLowerCase();
      let response = mockAiResponses.default;
      if (p.includes('analyst') || p.includes('score') || p.includes('sentiment')) {
        response = mockAiResponses.analysts;
      } else if (p.includes('schema') || p.includes('json') || p.includes('extract')) {
        response = mockAiResponses.extract;
      }
      setDemoResponse(response);
      setDemoPending(false);
      synth.playBlip();
    }, 1100);
  };

  const handleReconnect = () => {
    synth.playClick();
    setIsDisconnected(false);
    setDemoStep(0);
  };

  return (
    <div className="grid grid-cols-1 lg:grid-cols-12 gap-8 items-center max-w-6xl mx-auto w-full">
      <div className="lg:col-span-4 flex flex-col justify-center text-left">
        <span className="text-emerald-500 font-mono text-xs font-bold uppercase tracking-wider mb-2">// SOVEREIGN DISCONNECT</span>
        <h2 className="font-display font-bold text-2xl sm:text-3xl text-white tracking-tight uppercase leading-none mb-4">
          Live Offline Walkthrough
        </h2>
        <p className="text-slate-400 font-sans text-sm sm:text-base leading-relaxed mb-6">
          Witness absolute independence in motion. Flip the sovereign kill-switch to isolate your computing workspace and verify local cognitive offline processing in high-fidelity.
        </p>

        <div className="hidden lg:flex items-center gap-2 border border-slate-800/80 rounded px-3 py-1.5 bg-slate-900/50 text-[10px] font-mono text-slate-500">
          <Lock className="w-3.5 h-3.5 text-emerald-400 shrink-0 animate-pulse" />
          <span>Isolating terminal loops from network cards fully.</span>
        </div>
      </div>

      <div className="lg:col-span-8 flex flex-col w-full">
        <div className="bg-slate-950/60 border border-slate-800/80 rounded-xl p-5 sm:p-6 text-left flex flex-col gap-4">
          
          {!isDisconnected ? (
            <div className="flex flex-col items-center justify-center py-10 text-center">
              <WifiOff className="w-16 h-16 text-emerald-500/30 animate-pulse mb-6" />
              <h3 className="font-display font-bold text-lg text-white uppercase mb-2">OFF-GRID CONNECTION SANDBOX</h3>
              <p className="text-slate-400 text-xs font-sans max-w-md mb-8">
                Initiate off-grid mode to sever connection mapping hooks and activate offline model simulations on your local VRAM nodes.
              </p>
              <button
                onClick={handleSeverConnection}
                className="px-6 py-3 rounded bg-emerald-500 text-slate-950 font-mono text-xs font-black uppercase tracking-wider border border-emerald-400 hover:shadow-[0_0_20px_rgba(16,185,129,0.35)] cursor-pointer transition-all duration-300"
              >
                ⚡ ACTIVATE OFF-GRID INTERRUPT
              </button>
            </div>
          ) : (
            <div className="flex flex-col gap-4 h-full">
              <div className="flex items-center justify-between border-b border-slate-800 pb-2">
                <div className="flex items-center gap-2 text-[10px] font-mono font-bold text-emerald-400">
                  <span className="w-2 h-2 rounded-full bg-emerald-500 animate-pulse-emerald" />
                  <span>OFF-GRID SANDBOX ENVIRONMENT ACTIVE</span>
                </div>
                <button
                  onClick={handleReconnect}
                  className="font-mono text-[9px] text-slate-500 hover:text-slate-350 hover:underline"
                >
                  [RECONNECT NETWORK]
                </button>
              </div>

              <div className="bg-slate-900 rounded p-3 font-mono text-[10px] text-slate-300 h-32 overflow-y-auto custom-scrollbar flex flex-col gap-1.5 border border-slate-850">
                {demoLogs.map((log, idx) => (
                  <p key={idx} className={log.includes('Failed') || log.includes('Dead') ? 'text-rose-450 font-bold' : log.includes('Sovereign') ? 'text-emerald-400 font-bold' : ''}>
                    {log}
                  </p>
                ))}
                {demoStep === 1 && (
                  <div className="flex items-center gap-2 text-slate-500">
                    <span className="w-1.5 h-1.5 rounded-full bg-slate-500 animate-ping" />
                    <span>Severing network nodes...</span>
                  </div>
                )}
              </div>

              {demoStep === 2 && (
                <motion.form
                  initial={{ opacity: 0, y: 5 }}
                  animate={{ opacity: 1, y: 0 }}
                  onSubmit={submitDemoPrompt}
                  className="flex flex-col gap-3 font-mono"
                >
                  <div className="flex flex-col gap-1">
                    <label className="text-[9px] text-slate-500 uppercase">Test Sovereign Reasoning Invocations:</label>
                    <div className="flex gap-2">
                      <input
                        type="text"
                        value={demoPrompt}
                        onChange={(e) => setDemoPrompt(e.target.value)}
                        placeholder="Try prompt e.g.: 'Run Sentiment Score Matrix' or 'Extract JSON Schema'..."
                        className="flex-1 bg-slate-900 border border-slate-800 rounded px-3 py-2 text-xs text-white focus:outline-none focus:border-emerald-500"
                      />
                      <button
                        type="submit"
                        disabled={demoPending || !demoPrompt.trim()}
                        className="px-4 py-2 bg-emerald-500 text-slate-950 rounded font-black text-xs uppercase cursor-pointer hover:bg-emerald-400 disabled:opacity-50 disabled:cursor-not-allowed transition-colors"
                      >
                        {demoPending ? 'RUNNING...' : 'SUBMIT'}
                      </button>
                    </div>
                  </div>

                  {(demoPending || demoResponse) && (
                    <div className="bg-slate-950 rounded border border-slate-850 p-3 h-28 overflow-y-auto custom-scrollbar font-mono text-[10px]">
                      {demoPending ? (
                        <div className="flex items-center gap-2 text-slate-500">
                          <div className="w-3 h-3 border border-t-emerald-500 border-r-transparent rounded-full animate-spin" />
                          <span>Invoking local model weights... SEC Compliance sandbox isolation 100% verified</span>
                        </div>
                      ) : (
                        <pre className="text-emerald-400 break-words whitespace-pre-wrap">{demoResponse}</pre>
                      )}
                    </div>
                  )}
                </motion.form>
              )}
            </div>
          )}
        </div>
      </div>
    </div>
  );
}
