"use client";

import React, { useState, useRef, useEffect } from "react";
import Image from "next/image";
import { 
  MessageSquare, 
  X, 
  Send, 
  Sparkles, 
  Bot, 
  User, 
  RefreshCw, 
  Phone, 
  ExternalLink,
  MessageCircle,
  Minimize2,
  Maximize2,
  ChevronDown
} from "lucide-react";
import { useAppStore } from "@/lib/store";

interface Message {
  id: string;
  sender: "bot" | "user";
  text: string;
  timestamp: string;
}

const QUICK_PROMPTS = [
  "What services does AetherSoft offer?",
  "How much does a Next.js web application cost?",
  "Tell me about PharmaCore Pharmacy POS",
  "How fast can you start a development sprint?",
  "How do I schedule a technical consultation?",
];

export function ChatbotWidget() {
  const { siteSettings, formatPrice, services, products } = useAppStore();
  const chatbotConfig = siteSettings?.chatbot_config;

  const [isOpen, setIsOpen] = useState(false);
  const [messages, setMessages] = useState<Message[]>([]);
  const [inputValue, setInputValue] = useState("");
  const [isTyping, setIsTyping] = useState(false);
  const messagesEndRef = useRef<HTMLDivElement>(null);

  // Initialize with welcome message
  useEffect(() => {
    if (messages.length === 0) {
      setMessages([
        {
          id: "welcome-msg",
          sender: "bot",
          text: chatbotConfig?.welcome_message || 
            "Hello! I am AetherBot AI, your software solutions assistant. How can I assist with your web, mobile, SaaS, or bespoke enterprise project today?",
          timestamp: new Date().toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' }),
        }
      ]);
    }
  }, [chatbotConfig?.welcome_message]);

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

  if (chatbotConfig?.enabled === false) {
    return null;
  }

  const generateAIResponse = async (userQuery: string): Promise<string> => {
    const q = userQuery.toLowerCase();

    // 1. Check for custom API endpoint
    if (chatbotConfig?.api_endpoint && chatbotConfig.api_endpoint.startsWith("http")) {
      try {
        const res = await fetch(chatbotConfig.api_endpoint, {
          method: "POST",
          headers: {
            "Content-Type": "application/json",
            ...(chatbotConfig.api_key ? { "Authorization": `Bearer ${chatbotConfig.api_key}` } : {}),
          },
          body: JSON.stringify({
            message: userQuery,
            system_prompt: chatbotConfig.system_prompt,
          }),
        });
        if (res.ok) {
          const data = await res.json();
          if (data.reply || data.response || data.text || data.message) {
            return data.reply || data.response || data.text || data.message;
          }
        }
      } catch (err) {
        // Fallback to internal NLP engine
      }
    }

    // 2. Built-in AetherSoft Domain Intelligence NLP Engine
    if (q.includes("service") || q.includes("discipline") || q.includes("what do you do") || q.includes("offer")) {
      return `At AetherSoft Innovations, we engineer high-performance software across 5 core disciplines:\n\n1. **Web Engineering**: High-concurrency Next.js 14, React, Supabase & Node.js web applications.\n2. **Mobile Apps**: Flutter & React Native cross-platform iOS & Android apps.\n3. **SEO & Growth**: Technical Core Web Vitals, speed optimization & Search Engine ranking.\n4. **UI/UX Design**: High-fidelity Figma design tokens, wireframes & modern component libraries.\n5. **Custom SaaS & ERP**: Enterprise POS systems with offline SQLite sync and FBR fiscal integrations.`;
    }

    if (q.includes("cost") || q.includes("price") || q.includes("pricing") || q.includes("package") || q.includes("budget") || q.includes("rate")) {
      return `We provide 100% Fixed-Price guaranteed service packages with milestone-based escrow:\n\n• **Starter Package**: ${formatPrice("PKR 45,000")} (5 Core Pages, Next.js 14, Sub-35ms speed, 1-2 Weeks)\n• **Studio / Growth Package**: ${formatPrice("PKR 120,000")} (Full Web Platform + Mobile PWA, Database, Custom CMS, 2-3 Weeks)\n• **Enterprise Package**: ${formatPrice("PKR 280,000+")} (Full Stack Architecture, Dedicated Team, Custom APIs & 90-Day SLA Warranty)\n\nYou can also explore our interactive Sprint Cost Calculator on the Packages page!`;
    }

    if (q.includes("pharmacore") || q.includes("pharmacy") || q.includes("pos") || q.includes("medicine")) {
      return `**PharmaCore POS & ERP** is our flagship healthcare SaaS platform. Features include:\n• 100% Offline-First Desktop Runtime (Electron & SQLite)\n• Real-Time FBR Fiscal POS Invoice Sync\n• 35,000+ Pre-Indexed Pakistani Medicine Database\n• Barcode Scanning & Batch Expiry Tracking\n• Multi-Branch Inventory Reconciliation\n\nStarting at ${formatPrice("PKR 35,000")} one-time or PKR 4,500/mo. Would you like a live demonstration?`;
    }

    if (q.includes("aetherdine") || q.includes("restaurant") || q.includes("dining") || q.includes("kitchen")) {
      return `**AetherDine Restaurant OS** features Kitchen Display System (KDS), Table QR ordering, waiter tablet app, multi-tax splits, and automated daily profit/loss accounting.`;
    }

    if (q.includes("taleemi") || q.includes("school") || q.includes("student") || q.includes("education")) {
      return `**TaleemiNizaam School Management OS** automates student fee vouchers with 1-click WhatsApp PDF dispatch, automated grade reporting, teacher payroll, and biometric attendance.`;
    }

    if (q.includes("contact") || q.includes("schedule") || q.includes("consult") || q.includes("talk") || q.includes("call") || q.includes("phone") || q.includes("whatsapp")) {
      return `You can reach our engineering leads directly via:\n\n• **WhatsApp Hotline**: ${siteSettings?.contact_whatsapp || "+92 335 7758256"}\n• **Direct Phone**: ${siteSettings?.contact_phone || "+92 335 7758256"}\n• **Business Email**: ${siteSettings?.contact_email || "contact@aethersoftinnovations.com"}\n• **Location**: Software Technology Park, I-9, Islamabad, Pakistan.\n\nWould you like me to connect you with our Technical Architect right away?`;
    }

    if (q.includes("timeline") || q.includes("fast") || q.includes("start") || q.includes("how long")) {
      return `Our dedicated engineering pods initialize within **24 to 48 hours** after project scoping and deposit. We deliver staging preview builds on a weekly schedule with full access to your private Client Portal!`;
    }

    return `Thank you for your inquiry! Our Solutions Architects specialize in Next.js web applications, mobile platforms, and dedicated SaaS ecosystems.\n\nFeel free to explore our fixed packages, request an architecture audit, or tap the WhatsApp button below to chat with an engineer immediately.`;
  };

  const handleSendMessage = async (textToSend?: string) => {
    const query = (textToSend || inputValue).trim();
    if (!query) return;

    const userMsg: Message = {
      id: `msg-${Date.now()}`,
      sender: "user",
      text: query,
      timestamp: new Date().toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' }),
    };

    setMessages((prev) => [...prev, userMsg]);
    setInputValue("");
    setIsTyping(true);

    const delay = Math.min(1000, 400 + query.length * 8);

    setTimeout(async () => {
      const botReplyText = await generateAIResponse(query);
      setIsTyping(false);
      setMessages((prev) => [
        ...prev,
        {
          id: `bot-${Date.now()}`,
          sender: "bot",
          text: botReplyText,
          timestamp: new Date().toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' }),
        }
      ]);
    }, delay);
  };

  const handleResetChat = () => {
    setMessages([
      {
        id: `welcome-${Date.now()}`,
        sender: "bot",
        text: chatbotConfig?.welcome_message || "Hello! How can I assist with your software development requirements today?",
        timestamp: new Date().toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' }),
      }
    ]);
  };

  return (
    <>
      {/* FLOATING TRIGGER BUTTON */}
      {!isOpen && (
        <div className="fixed bottom-6 right-6 z-50 animate-in fade-in zoom-in duration-300">
          <button
            onClick={() => setIsOpen(true)}
            className="group relative flex items-center gap-3 rounded-full bg-[#024d37] pl-4 pr-5 py-3.5 text-white shadow-2xl shadow-[#024d37]/40 hover:bg-[#036549] hover:scale-105 active:scale-95 transition-all cursor-pointer border border-emerald-400/30 font-sans"
            aria-label="Open AI Live Assistant"
          >
            <div className="relative">
              <div className="h-9 w-9 rounded-full bg-white/15 flex items-center justify-center border border-white/25">
                <Bot className="h-5 w-5 text-emerald-300 group-hover:rotate-12 transition-transform" />
              </div>
              <span className="absolute -top-0.5 -right-0.5 h-3 w-3 rounded-full bg-emerald-400 border-2 border-[#024d37] animate-ping" />
              <span className="absolute -top-0.5 -right-0.5 h-3 w-3 rounded-full bg-emerald-400 border-2 border-[#024d37]" />
            </div>

            <div className="text-left font-mono">
              <div className="text-xs font-bold tracking-wide flex items-center gap-1.5">
                <span>{chatbotConfig?.bot_name || "AetherBot AI"}</span>
                <Sparkles className="h-3 w-3 text-emerald-300" />
              </div>
              <div className="text-[10px] text-white/80">Online • Ask any question</div>
            </div>
          </button>
        </div>
      )}

      {/* EXPANDED CHAT PANEL */}
      {isOpen && (
        <div className="fixed bottom-4 right-4 sm:bottom-6 sm:right-6 z-50 w-[calc(100vw-2rem)] sm:w-[400px] h-[580px] max-h-[85vh] rounded-3xl border border-border bg-card shadow-2xl flex flex-col overflow-hidden animate-in fade-in slide-in-from-bottom-6 duration-300 font-sans">
          {/* Top Bar Header */}
          <div className="bg-[#024d37] text-white p-4 flex items-center justify-between border-b border-[#036549] shrink-0">
            <div className="flex items-center gap-3">
              <div className="relative h-10 w-10 rounded-2xl bg-white/10 border border-white/20 p-1.5 flex items-center justify-center shrink-0">
                <Image
                  src={chatbotConfig?.avatar_url || siteSettings?.logo_url || "/assets/logo/logo.png"}
                  alt="AetherBot Avatar"
                  width={32}
                  height={32}
                  className="object-contain"
                />
                <span className="absolute -bottom-0.5 -right-0.5 h-3 w-3 rounded-full bg-emerald-400 border-2 border-[#024d37]" />
              </div>
              <div>
                <div className="font-bold text-sm flex items-center gap-1.5">
                  <span>{chatbotConfig?.bot_name || "AetherBot AI"}</span>
                  <span className="rounded-full bg-white/20 px-2 py-0.2 font-mono text-[9px] uppercase font-bold text-emerald-200">
                    Active
                  </span>
                </div>
                <div className="text-[11px] font-mono text-white/75">
                  AetherSoft Technical AI
                </div>
              </div>
            </div>

            <div className="flex items-center gap-1">
              <button
                onClick={handleResetChat}
                title="Reset conversation"
                className="p-2 text-white/70 hover:text-white rounded-lg hover:bg-white/10 transition-colors cursor-pointer"
              >
                <RefreshCw className="h-4 w-4" />
              </button>
              <button
                onClick={() => setIsOpen(false)}
                title="Close chat"
                className="p-2 text-white/70 hover:text-white rounded-lg hover:bg-white/10 transition-colors cursor-pointer"
              >
                <X className="h-4 w-4" />
              </button>
            </div>
          </div>

          {/* Chat Messages Body */}
          <div className="flex-1 overflow-y-auto p-4 space-y-3.5 bg-muted/20">
            {messages.map((msg) => (
              <div
                key={msg.id}
                className={`flex gap-2.5 ${msg.sender === "user" ? "justify-end" : "justify-start"}`}
              >
                {msg.sender === "bot" && (
                  <div className="h-7 w-7 rounded-xl bg-[#024d37] text-white flex items-center justify-center shrink-0 mt-1 shadow-xs">
                    <Bot className="h-4 w-4 text-emerald-300" />
                  </div>
                )}

                <div
                  className={`max-w-[82%] rounded-2xl p-3.5 text-xs leading-relaxed ${
                    msg.sender === "user"
                      ? "bg-[#024d37] text-white rounded-br-xs font-sans shadow-sm"
                      : "bg-card border border-border text-foreground rounded-tl-xs shadow-xs"
                  }`}
                >
                  <div className="whitespace-pre-wrap">{msg.text}</div>
                  <div
                    className={`mt-1.5 font-mono text-[10px] text-right ${
                      msg.sender === "user" ? "text-white/70" : "text-muted-foreground"
                    }`}
                  >
                    {msg.timestamp}
                  </div>
                </div>

                {msg.sender === "user" && (
                  <div className="h-7 w-7 rounded-xl bg-muted border border-border text-foreground flex items-center justify-center shrink-0 mt-1 shadow-xs">
                    <User className="h-4 w-4 text-muted-foreground" />
                  </div>
                )}
              </div>
            ))}

            {isTyping && (
              <div className="flex gap-2.5 items-center justify-start">
                <div className="h-7 w-7 rounded-xl bg-[#024d37] text-white flex items-center justify-center shrink-0 shadow-xs">
                  <Bot className="h-4 w-4 text-emerald-300" />
                </div>
                <div className="rounded-2xl rounded-tl-xs bg-card border border-border p-3.5 flex items-center gap-1.5 shadow-xs">
                  <span className="h-2 w-2 rounded-full bg-[#024d37] animate-bounce" />
                  <span className="h-2 w-2 rounded-full bg-[#024d37] animate-bounce [animation-delay:0.2s]" />
                  <span className="h-2 w-2 rounded-full bg-[#024d37] animate-bounce [animation-delay:0.4s]" />
                </div>
              </div>
            )}

            <div ref={messagesEndRef} />
          </div>

          {/* Quick Prompts Carousel */}
          {messages.length <= 2 && (
            <div className="px-4 py-2 border-t border-border bg-card overflow-x-auto flex gap-1.5 shrink-0 no-scrollbar">
              {QUICK_PROMPTS.map((prompt, idx) => (
                <button
                  key={idx}
                  onClick={() => handleSendMessage(prompt)}
                  className="shrink-0 text-[11px] font-mono rounded-full border border-border bg-muted/60 px-3 py-1 text-muted-foreground hover:text-foreground hover:border-[#024d37] hover:bg-[#024d37]/10 transition-colors cursor-pointer"
                >
                  {prompt}
                </button>
              ))}
            </div>
          )}

          {/* Message Input & Action Bar */}
          <div className="p-3 border-t border-border bg-card space-y-2 shrink-0">
            <form
              onSubmit={(e) => {
                e.preventDefault();
                handleSendMessage();
              }}
              className="flex items-center gap-2"
            >
              <input
                type="text"
                placeholder="Ask about web, mobile, SaaS or pricing..."
                value={inputValue}
                onChange={(e) => setInputValue(e.target.value)}
                className="flex-1 rounded-2xl border border-border bg-muted px-4 py-2.5 text-xs text-foreground focus:border-[#024d37] focus:outline-none font-sans"
              />
              <button
                type="submit"
                disabled={!inputValue.trim() || isTyping}
                className="h-9 w-9 rounded-2xl bg-[#024d37] text-white flex items-center justify-center hover:bg-[#036549] transition-all disabled:opacity-50 cursor-pointer shrink-0 shadow-md shadow-[#024d37]/20"
                aria-label="Send Message"
              >
                <Send className="h-4 w-4" />
              </button>
            </form>

            <div className="flex items-center justify-between font-mono text-[10px] text-muted-foreground px-1">
              <span className="flex items-center gap-1">
                <span className="h-1.5 w-1.5 rounded-full bg-emerald-500" />
                <span>AI Scoping Engine</span>
              </span>

              {chatbotConfig?.fallback_whatsapp && (
                <a
                  href={`https://wa.me/${chatbotConfig.fallback_whatsapp.replace(/[^0-9]/g, "")}`}
                  target="_blank"
                  rel="noopener noreferrer"
                  className="text-[#024d37] font-semibold hover:underline flex items-center gap-1"
                >
                  <MessageCircle className="h-3 w-3 text-[#25d366]" />
                  <span>Chat on WhatsApp →</span>
                </a>
              )}
            </div>
          </div>
        </div>
      )}
    </>
  );
}
