"use client";
import React, { useState, useEffect, useRef } from "react";
import { motion, AnimatePresence } from "framer-motion";
import { Sparkles, X, Terminal, ArrowRight, Minimize2 } from "lucide-react";

interface Message {
  id: string;
  sender: "user" | "ai";
  text: string;
  isConsole?: boolean;
}

const CHAT_SUGGESTIONS = [
  { text: "What is EMS?", prompt: "What is EMS?" },
  { text: "Predictive Maintenance", prompt: "What is predictive maintenance?" },
  { text: "Carbon Monitoring", prompt: "How does carbon monitoring work?" },
  { text: "Industrial Protocols", prompt: "Which industrial protocols are supported?" },
  { text: "Harmonic Distortion", prompt: "What is harmonic distortion?" },
  { text: "How Orbit AI works", prompt: "How does Orbit AI work?" },
  { text: "Request a Demo", prompt: "How to request a demo?" },
  { text: "Contact Support", prompt: "How to contact support?" },
  { text: "Orbit AI Modules", prompt: "Explain the specialized AI agents." }
];

export function AIAssistant() {
  const [isOpen, setIsOpen] = useState(false);
  const [isMinimized, setIsMinimized] = useState(false);
  const [messages, setMessages] = useState<Message[]>([
    {
      id: "init",
      sender: "ai",
      text: "SYS_CORE: Orbit AI Engineer Co-Pilot online.\n>> Connected to regional edge registers & standards DB.\n>> Type your query or choose an automated diagnostic path below.",
      isConsole: true
    },
  ]);
  const [isTyping, setIsTyping] = useState(false);
  const [userInput, setUserInput] = useState("");
  const consoleEndRef = useRef<HTMLDivElement>(null);

  useEffect(() => {
    if (consoleEndRef.current) {
      consoleEndRef.current.scrollIntoView({ behavior: "smooth" });
    }
  }, [messages, isTyping]);

  const simulateAIResponse = (promptText: string) => {
    setIsTyping(true);
    let replyText = "";
    const cleanPrompt = promptText.toLowerCase().trim();

    // Mapping conversational triggers to RAG Knowledge Base definitions
    if (cleanPrompt.includes("ems") || cleanPrompt.includes("energy")) {
      replyText = "[SYS_INFO: INGESTING /ai/chatbot/knowledge/ems.md]\n" +
                  ">> Orbit EMS correlates electricity, gas, and steam telemetry with active manufacturing SKUs to determine Specific Energy Consumption (SEC).\n" +
                  ">> Specific target: ISO 50001 compliance and IPMVP Option B audits.\n" +
                  ">> Peak Shaving: Shaves up to 28.4% off active loads by predictive demand limit thresholds and PLC starting sequence overrides.";
    } else if (cleanPrompt.includes("predictive") || cleanPrompt.includes("maintenance") || cleanPrompt.includes("rul")) {
      replyText = "[SYS_INFO: INGESTING /ai/chatbot/knowledge/predictive-maintenance.md]\n" +
                  ">> Predictive AI models the Remaining Useful Life (RUL) of high-value rotating assets (bearing turbines, compressors, raw mills) using LSTMs.\n" +
                  ">> FFT Acoustics: Runs 1024-point Fast Fourier Transform axial vibration scans to isolate micro-cracks before unplanned structural halts occur.\n" +
                  ">> Target ROI: Average MTTR cuts of 35% and asset lifetime extension.";
    } else if (cleanPrompt.includes("carbon") || cleanPrompt.includes("esg") || cleanPrompt.includes("csrd")) {
      replyText = "[SYS_INFO: INGESTING /ai/chatbot/knowledge/carbon-monitoring.md]\n" +
                  ">> Orbit AI Carbon compiles double-entry carbon ledgers covering Scope 1 (direct combustion), Scope 2 (purchased utility grid), and Scope 3 (supplier value chain) emissions.\n" +
                  ">> Compliance: Perfect alignment with European CSRD regulations and CBAM carbon export tax registers.\n" +
                  ">> Live offsets: Allocates green PV generation from SFBT arrays in real-time.";
    } else if (cleanPrompt.includes("protocol") || cleanPrompt.includes("protocols") || cleanPrompt.includes("connectivity")) {
      replyText = "[SYS_INFO: INGESTING /ai/chatbot/knowledge/industrial-iot.md]\n" +
                  ">> Supported native industrial buses: Modbus TCP/RTU, OPC-UA namespaces, Siemens S7-1200/1500 PLC datablocks, BACnet/IP, and EtherNet/IP.\n" +
                  ">> Transmission: Real-time data compression and outbound-only TLS 1.3 MQTT streams on Port 8883/443 (meets IEC 62443 SL3 requirements).";
    } else if (cleanPrompt.includes("harmonic") || cleanPrompt.includes("distortion") || cleanPrompt.includes("thd")) {
      replyText = "[SYS_INFO: INGESTING /ai/chatbot/simulation/harmonic-analysis-example.md]\n" +
                  ">> Total Harmonic Distortion (THD) measures electrical switching noise generated by VFDs.\n" +
                  ">> Sizing: Orbit AI Power Quality computes phase inverse currents to cancel distortions.\n" +
                  ">> Compliance: Restores noisy currents (THDI 14% -> 3.8%) in full compliance with IEEE 519-2022 standards (< 5% THDV).";
    } else if (cleanPrompt.includes("work") || cleanPrompt.includes("orbit ai") || cleanPrompt.includes("how does")) {
      replyText = "[SYS_INFO: INGESTING /ai/chatbot/agents/agent-architecture.md]\n" +
                  ">> Orbit AI operates as a hybrid Multi-Agent AI System.\n" +
                  ">> Coordination: A Central Coordination Engine routes operator inquiries in real-time to specialized agents (AI Energy, AI Carbon, AI Maintenance, AI Power Quality, etc.).\n" +
                  ">> Advantage: Ensures audit-ready, regulatory-grade responses instead of vague LLM hallucinations.";
    } else if (cleanPrompt.includes("demo") || cleanPrompt.includes("schedule") || cleanPrompt.includes("book")) {
      replyText = "[SYS_ACTION: REDIRECT_SCHEDULER]\n" +
                  ">> Book a dynamic high-fidelity NOC telemetry tour to see our live compressor twins.\n" +
                  ">> Go to /demo to select your preferred date slot.";
    } else if (cleanPrompt.includes("support") || cleanPrompt.includes("contact") || cleanPrompt.includes("sla")) {
      replyText = "[SYS_SUPPORT: INGESTING /ai/chatbot/faq/faq-database.json]\n" +
                  ">> Emergency response: Tunis NOC phone: +216 36 086 006 / email: noc@orbit-solutions.com.\n" +
                  ">> SLA structure: 15-minute interlock times and hot-swappable edge gateway hardware.\n" +
                  ">> Submit a direct ticket in the client dashboard under /portal/ticketing.";
    } else if (cleanPrompt.includes("industries") || cleanPrompt.includes("sector") || cleanPrompt.includes("supported")) {
      replyText = "[SYS_INFO: INGESTING /ai/chatbot/knowledge/orbit-solutions.md]\n" +
                  ">> Optimized industries: Automotive stamping, Food & Beverage HACCP zones, Pharmaceutical cleanrooms, PV solar generation, textile looms, and cogeneration plants.\n" +
                  ">> Live cases: MLIHA, DIARI, ACN, Warda, L'Epi d'Or, Spiga, Délice, Danone, Cap d'Or, abids, BioPak, Fromagère.";
    } else if (cleanPrompt.includes("agents") || cleanPrompt.includes("modules") || cleanPrompt.includes("specialized")) {
      replyText = "[SYS_INFO: INGESTING /ai/chatbot/agents/agent-architecture.md]\n" +
                  ">> Core AI Modules:\n" +
                  " 1. Orbit AI Energy: ISO 50001 SEC baselines\n" +
                  " 2. Orbit AI Carbon: Scope 1/2/3 ESG ledgers\n" +
                  " 3. Orbit AI Maintenance: LSTM bearing RUL & FFT vibration\n" +
                  " 4. Orbit AI Manufacturing: Shift-level OEE and packaging halts\n" +
                  " 5. Orbit AI Process: Kiln thermal monitoring & raw mill correlations\n" +
                  " 6. Orbit AI Power Quality: IEEE 519 active filter simulations";
    } else {
      replyText = "[SYS_ALERT: Live node scan active]\n" +
                  ">> Pinging 12 active edge gateways (Mean Latency: 1.1ms).\n" +
                  ">> Warning: High harmonic distortion detected on Feeder A.\n" +
                  ">> Type 'harmonic distortion' to run an IEEE 519 compliance audit simulation.";
    }

    setTimeout(() => {
      setIsTyping(false);
      setMessages((prev) => [
        ...prev,
        {
          id: Math.random().toString(),
          sender: "ai",
          text: replyText,
          isConsole: true,
        },
      ]);
    }, 1200);
  };

  const handleSend = (textToSend: string) => {
    if (!textToSend.trim()) return;

    setMessages((prev) => [
      ...prev,
      {
        id: Math.random().toString(),
        sender: "user",
        text: textToSend,
      },
    ]);
    setUserInput("");
    simulateAIResponse(textToSend);
  };

  return (
    <div className="fixed bottom-6 right-6 z-50">
      {/* Expanded Console Window */}
      <AnimatePresence>
        {isOpen && !isMinimized && (
          <motion.div
            initial={{ opacity: 0, scale: 0.9, y: 50 }}
            animate={{ opacity: 1, scale: 1, y: 0 }}
            exit={{ opacity: 0, scale: 0.9, y: 50 }}
            className="mb-4 h-[485px] w-[340px] md:w-[390px] overflow-hidden rounded-3xl border border-slate-200 bg-white/95 p-5 shadow-2xl backdrop-blur-2xl flex flex-col justify-between dark:border-slate-800 dark:bg-black/95"
          >
            {/* Header */}
            <div className="flex items-center justify-between border-b border-slate-100 pb-3 dark:border-slate-800">
              <div className="flex items-center gap-2">
                <span className="relative flex h-2 w-2">
                  <span className="absolute inline-flex h-full w-full animate-ping rounded-full bg-orbit-cyan opacity-75"></span>
                  <span className="relative inline-flex h-2 w-2 rounded-full bg-orbit-cyan"></span>
                </span>
                <span className="font-mono text-[10px] font-bold tracking-widest text-slate-800 flex items-center gap-1 dark:text-white">
                  ORBIT_AI_ASSISTANT_V4
                </span>
              </div>
              <div className="flex items-center gap-1.5">
                <button
                  onClick={() => setIsMinimized(true)}
                  className="flex h-6 w-6 items-center justify-center rounded-full border border-slate-200 bg-slate-50 text-slate-500 hover:text-slate-900 transition-colors dark:border-slate-800 dark:bg-slate-950 dark:text-slate-400 dark:hover:text-white"
                  title="Minimize"
                >
                  <Minimize2 className="h-3 w-3" />
                </button>
                <button
                  onClick={() => setIsOpen(false)}
                  className="flex h-6 w-6 items-center justify-center rounded-full border border-slate-200 bg-slate-50 text-slate-500 hover:text-slate-900 transition-colors dark:border-slate-800 dark:bg-slate-950 dark:text-slate-400 dark:hover:text-white"
                  title="Close"
                >
                  <X className="h-3.5 w-3.5" />
                </button>
              </div>
            </div>

            {/* Conversation Log */}
            <div className="flex-1 overflow-y-auto py-3 space-y-3 pr-1 min-h-[220px]">
              {messages.map((msg) => (
                <div
                  key={msg.id}
                  className={`flex ${msg.sender === "user" ? "justify-end" : "justify-start"}`}
                >
                  <div
                    className={`max-w-[88%] rounded-2xl p-3 text-xs leading-relaxed ${
                      msg.sender === "user"
                        ? "bg-orbit-cyan/10 text-slate-800 border border-orbit-cyan/20 font-sans shadow-sm dark:bg-orbit-cyan/20 dark:text-white"
                        : msg.isConsole
                        ? "bg-slate-950 font-mono border border-slate-900 text-emerald-400 whitespace-pre-line text-[11px] shadow-inner dark:border-slate-800"
                        : "bg-slate-50 text-slate-700 border border-slate-200/80 font-sans shadow-sm dark:bg-slate-900/60 dark:text-slate-200 dark:border-slate-800"
                    }`}
                  >
                    {msg.text}
                  </div>
                </div>
              ))}

              {isTyping && (
                <div className="flex justify-start">
                  <div className="flex items-center gap-1.5 rounded-2xl bg-slate-950 border border-slate-900 p-3 text-emerald-400 font-mono text-[11px] shadow-inner dark:border-slate-800">
                    <Terminal className="h-3.5 w-3.5 animate-pulse" />
                    <span>Orchestrating multi-agent retrieval...</span>
                  </div>
                </div>
              )}
              <div ref={consoleEndRef} />
            </div>

            {/* Footer Form & Quick Suggestions */}
            <div className="border-t border-slate-100 pt-3 dark:border-slate-800">
              {/* Quick Pills (Horizontally Scrollable) */}
              {!isTyping && (
                <div className="mb-3 flex gap-1.5 overflow-x-auto pb-1 scrollbar-none snap-x snap-mandatory max-h-[32px]">
                  {CHAT_SUGGESTIONS.map((sug) => (
                    <button
                      key={sug.text}
                      onClick={() => {
                        setMessages((prev) => [...prev, { id: Math.random().toString(), sender: "user", text: sug.text }]);
                        simulateAIResponse(sug.prompt);
                      }}
                      className="shrink-0 snap-center rounded-full border border-slate-200 bg-slate-50 px-2.5 py-1 font-mono text-[9px] font-semibold text-orbit-cyan hover:border-orbit-cyan hover:bg-orbit-cyan/5 transition-all dark:border-slate-800 dark:bg-slate-900/60"
                    >
                      {sug.text}
                    </button>
                  ))}
                </div>
              )}

              {/* Text Form */}
              <form
                onSubmit={(e) => {
                  e.preventDefault();
                  handleSend(userInput);
                }}
                className="flex items-center gap-2 rounded-full border border-slate-200 bg-slate-50 p-1 pl-3 dark:border-slate-800 dark:bg-slate-950"
              >
                <input
                  type="text"
                  value={userInput}
                  onChange={(e) => setUserInput(e.target.value)}
                  placeholder="Ask a technical question..."
                  className="w-full bg-transparent font-sans text-xs text-slate-800 placeholder-slate-400 focus:outline-none dark:text-white"
                />
                <button
                  type="submit"
                  className="flex h-7 w-7 items-center justify-center rounded-full bg-gradient-to-r from-orbit-cyan to-orbit-purple text-white shadow-md active:scale-95 transition-transform"
                >
                  <ArrowRight className="h-3.5 w-3.5" />
                </button>
              </form>
            </div>
          </motion.div>
        )}
      </AnimatePresence>

      {/* Minimized Docked Tab */}
      <AnimatePresence>
        {isOpen && isMinimized && (
          <motion.div
            initial={{ opacity: 0, y: 50 }}
            animate={{ opacity: 1, y: 0 }}
            exit={{ opacity: 0, y: 50 }}
            onClick={() => setIsMinimized(false)}
            className="mb-4 flex cursor-pointer items-center justify-between gap-4 rounded-full border border-slate-200 bg-white/95 px-4 py-2 shadow-2xl backdrop-blur-md hover:border-orbit-cyan/30 transition-colors dark:border-slate-800 dark:bg-black/95"
          >
            <div className="flex items-center gap-2">
              <span className="relative flex h-2 w-2">
                <span className="absolute inline-flex h-full w-full animate-ping rounded-full bg-orbit-cyan opacity-75"></span>
                <span className="relative inline-flex h-2 w-2 rounded-full bg-orbit-cyan"></span>
              </span>
              <span className="font-mono text-[9px] font-bold text-slate-700 dark:text-slate-300">ORBIT_CO-PILOT (MINIMIZED)</span>
            </div>
            <button
              onClick={(e) => {
                e.stopPropagation();
                setIsOpen(false);
                setIsMinimized(false);
              }}
              className="flex h-4 w-4 items-center justify-center rounded-full text-slate-600 dark:text-slate-400 hover:text-slate-700 dark:hover:text-slate-900 dark:text-white"
            >
              <X className="h-3 w-3" />
            </button>
          </motion.div>
        )}
      </AnimatePresence>

      {/* Floating Orb Toggle Button */}
      <button
        onClick={() => {
          if (isOpen && isMinimized) {
            setIsMinimized(false);
          } else {
            setIsOpen(!isOpen);
          }
        }}
        className="group relative flex h-14 w-14 items-center justify-center rounded-full bg-slate-50 dark:bg-black p-[2px] transition-transform duration-300 hover:scale-105 active:scale-95 focus:outline-none shadow-lg border border-slate-200/80 dark:border-slate-800"
        aria-label="Orbit AI Co-Pilot"
      >
        {/* Glow halo */}
        <div className="absolute inset-[-4px] rounded-full bg-gradient-to-br from-orbit-cyan via-orbit-blue to-orbit-purple opacity-40 blur-md group-hover:opacity-75 transition-opacity" />
        
        {/* Animated Dash Rotating Rings */}
        <div className="absolute inset-0 rounded-full border border-dashed border-orbit-cyan/30 animate-[spin_12s_linear_infinite] group-hover:border-orbit-cyan/50" />
        <div className="absolute inset-[3px] rounded-full border border-dashed border-orbit-purple/30 animate-[spin_8s_linear_infinite_reverse]" />

        {/* Breathing Inner Sphere */}
        <div className="relative flex h-full w-full items-center justify-center rounded-full bg-white dark:bg-slate-950">
          <Sparkles className="h-5 w-5 text-orbit-cyan animate-pulse group-hover:text-orbit-blue transition-colors" />
        </div>
      </button>
    </div>
  );
}
