"use client";

import { useState, useRef, useEffect } from "react";
import { motion, AnimatePresence } from "framer-motion";
import { MessageCircle, X, Send, Bot, User, Sparkles, HelpCircle } from "lucide-react";

interface Message {
  role: "user" | "assistant";
  content: string;
}

const QUICK_QUESTIONS = [
  "Bagaimana cara top up?",
  "Metode pembayaran apa saja?",
  "Bagaimana cara cek status pesanan?",
  "Apakah ada promo?",
];

export default function ChatWidget() {
  const [isOpen, setIsOpen] = useState(false);
  const [messages, setMessages] = useState<Message[]>([]);
  const [input, setInput] = useState("");
  const [isLoading, setIsLoading] = useState(false);
  const [activeTab, setActiveTab] = useState<"home" | "chat" | "faq">("home");
  const scrollRef = useRef<HTMLDivElement>(null);

  useEffect(() => {
    if (scrollRef.current) {
      scrollRef.current.scrollTop = scrollRef.current.scrollHeight;
    }
  }, [messages]);

  const sendMessage = async (text: string) => {
    if (!text.trim()) return;

    const userMsg: Message = { role: "user", content: text.trim() };
    const newMessages = [...messages, userMsg];
    setMessages(newMessages);
    setInput("");
    setIsLoading(true);
    setActiveTab("chat");

    try {
      const API_URL = process.env.NEXT_PUBLIC_API_URL ;
      const res = await fetch(`${API_URL}/api/v2/chat`, {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({
          messages: newMessages.map((m) => ({ role: m.role, content: m.content })),
        }),
      });
      const data = await res.json();
      if (data.success) {
        setMessages([...newMessages, { role: "assistant", content: data.reply }]);
      } else {
        setMessages([...newMessages, { role: "assistant", content: "Maaf, terjadi kesalahan. Silakan coba lagi. 🙏" }]);
      }
    } catch {
      setMessages([...newMessages, { role: "assistant", content: "Maaf, layanan sedang gangguan. Hubungi admin via WhatsApp. 📞" }]);
    } finally {
      setIsLoading(false);
    }
  };

  return (
    <>
      {/* Floating Button */}
      <AnimatePresence>
        {!isOpen && (
          <motion.button
            initial={{ scale: 0 }}
            animate={{ scale: 1 }}
            exit={{ scale: 0 }}
            onClick={() => setIsOpen(true)}
            className="fixed bottom-20 lg:bottom-6 right-4 z-50 w-14 h-14 rounded-full bg-gradient-to-br from-primary to-orange-600 text-white shadow-lg shadow-primary/30 flex items-center justify-center hover:scale-110 transition-transform"
          >
            <MessageCircle size={24} />
            {/* Pulse ring */}
            <span className="absolute inset-0 rounded-full bg-primary/30 animate-ping" />
          </motion.button>
        )}
      </AnimatePresence>

      {/* Chat Panel */}
      <AnimatePresence>
        {isOpen && (
          <motion.div
            initial={{ opacity: 0, y: 20, scale: 0.9 }}
            animate={{ opacity: 1, y: 0, scale: 1 }}
            exit={{ opacity: 0, y: 20, scale: 0.9 }}
            transition={{ type: "spring", damping: 25, stiffness: 300 }}
            className="fixed bottom-20 lg:bottom-6 right-4 z-50 w-[360px] max-w-[calc(100vw-2rem)] h-[520px] max-h-[calc(100vh-6rem)] rounded-2xl overflow-hidden shadow-2xl shadow-black/40 border border-dark-border flex flex-col bg-dark-surface"
          >
            {/* Header */}
            <div className="bg-gradient-to-r from-primary to-orange-600 px-4 py-3 flex items-center justify-between shrink-0">
              <div className="flex items-center gap-3">
                <div className="w-9 h-9 rounded-full bg-white/20 backdrop-blur-sm flex items-center justify-center overflow-hidden">
                  <img src="/images/assets/ai_assistant_avatar.webp" alt="ZxuanBot" className="w-full h-full object-cover" />
                </div>
                <div>
                  <h3 className="text-sm font-bold text-white flex items-center gap-1">
                    <Sparkles size={12} /> ZxuanBot
                  </h3>
                  <p className="text-[10px] text-white/70">Asisten AI • Online</p>
                </div>
              </div>
              <button
                onClick={() => setIsOpen(false)}
                className="w-8 h-8 rounded-full bg-white/15 hover:bg-white/25 flex items-center justify-center text-white transition-colors"
              >
                <X size={16} />
              </button>
            </div>

            {/* Body */}
            <div className="flex-1 overflow-hidden flex flex-col">
              {activeTab === "home" && (
                <div className="flex-1 p-4 overflow-y-auto">
                  {/* Welcome */}
                  <div className="text-center mb-6 mt-2">
                    <div className="text-4xl mb-2">👋</div>
                    <h4 className="text-base font-bold text-white">Halo!</h4>
                    <p className="text-xs text-muted mt-1">Ada yang bisa ZxuanBot bantu?</p>
                  </div>

                  {/* Quick Actions */}
                  <button
                    onClick={() => setActiveTab("chat")}
                    className="w-full flex items-center gap-3 p-3 rounded-xl bg-dark-surface2 border border-dark-border hover:border-primary/30 transition-all mb-2 group"
                  >
                    <div className="w-8 h-8 rounded-lg bg-primary/20 flex items-center justify-center">
                      <HelpCircle size={16} className="text-primary" />
                    </div>
                    <div className="text-left flex-1">
                      <p className="text-xs font-semibold text-white">Punya pertanyaan?</p>
                      <p className="text-[10px] text-muted">Tanyakan seputar layanan kami</p>
                    </div>
                    <Send size={14} className="text-muted group-hover:text-primary transition-colors" />
                  </button>

                  <a
                    href="https://wa.me/6281359123789"
                    target="_blank"
                    rel="noopener"
                    className="w-full flex items-center gap-3 p-3 rounded-xl bg-dark-surface2 border border-dark-border hover:border-green-500/30 transition-all group"
                  >
                    <div className="w-8 h-8 rounded-lg overflow-hidden bg-green-500/20 flex items-center justify-center">
                      <span className="text-base">💬</span>
                    </div>
                    <div className="text-left flex-1">
                      <p className="text-xs font-semibold text-white">Butuh bantuan?</p>
                      <p className="text-[10px] text-muted">Hubungi admin via WhatsApp</p>
                    </div>
                  </a>
                </div>
              )}

              {activeTab === "chat" && (
                <>
                  <div ref={scrollRef} className="flex-1 p-4 overflow-y-auto space-y-3">
                    {messages.length === 0 && (
                      <div className="space-y-2">
                        <p className="text-xs text-muted text-center mb-3">Pertanyaan populer:</p>
                        {QUICK_QUESTIONS.map((q) => (
                          <button
                            key={q}
                            onClick={() => sendMessage(q)}
                            className="w-full text-left px-3 py-2.5 rounded-xl bg-dark-surface2 border border-dark-border text-xs text-muted hover:text-white hover:border-primary/30 transition-all"
                          >
                            {q}
                          </button>
                        ))}
                      </div>
                    )}

                    {messages.map((msg, i) => (
                      <div key={i} className={`flex gap-2 ${msg.role === "user" ? "justify-end" : "justify-start"}`}>
                        {msg.role === "assistant" && (
                          <div className="w-7 h-7 rounded-full bg-primary/20 flex items-center justify-center shrink-0 mt-0.5">
                            <Bot size={14} className="text-primary" />
                          </div>
                        )}
                        <div
                          className={`max-w-[75%] px-3 py-2.5 rounded-2xl text-xs leading-relaxed ${
                            msg.role === "user"
                              ? "bg-primary text-white rounded-br-md"
                              : "bg-dark-surface2 text-white/90 border border-dark-border rounded-bl-md"
                          }`}
                        >
                          {msg.content}
                        </div>
                        {msg.role === "user" && (
                          <div className="w-7 h-7 rounded-full bg-dark-surface2 border border-dark-border flex items-center justify-center shrink-0 mt-0.5">
                            <User size={14} className="text-muted" />
                          </div>
                        )}
                      </div>
                    ))}

                    {isLoading && (
                      <div className="flex gap-2 items-start">
                        <div className="w-7 h-7 rounded-full bg-primary/20 flex items-center justify-center shrink-0">
                          <Bot size={14} className="text-primary" />
                        </div>
                        <div className="bg-dark-surface2 border border-dark-border rounded-2xl rounded-bl-md px-4 py-3">
                          <div className="flex gap-1">
                            <span className="w-2 h-2 rounded-full bg-muted animate-bounce" style={{ animationDelay: "0ms" }} />
                            <span className="w-2 h-2 rounded-full bg-muted animate-bounce" style={{ animationDelay: "150ms" }} />
                            <span className="w-2 h-2 rounded-full bg-muted animate-bounce" style={{ animationDelay: "300ms" }} />
                          </div>
                        </div>
                      </div>
                    )}
                  </div>
                </>
              )}
            </div>

            {/* Input bar (always visible when on chat tab or home) */}
            {activeTab === "chat" && (
              <form
                onSubmit={(e) => { e.preventDefault(); sendMessage(input); }}
                className="p-3 border-t border-dark-border flex items-center gap-2 shrink-0"
              >
                <input
                  value={input}
                  onChange={(e) => setInput(e.target.value)}
                  placeholder="Ketik pertanyaan..."
                  className="flex-1 bg-dark-surface2 border border-dark-border rounded-xl px-3 py-2.5 text-xs text-white placeholder-muted focus:outline-none focus:border-primary/50 transition-colors"
                  disabled={isLoading}
                />
                <button
                  type="submit"
                  disabled={isLoading || !input.trim()}
                  className="w-9 h-9 rounded-xl bg-primary hover:bg-primary-hover disabled:opacity-50 flex items-center justify-center text-white transition-all shrink-0"
                >
                  <Send size={14} />
                </button>
              </form>
            )}

            {/* Bottom Tab Bar */}
            <div className="flex items-center border-t border-dark-border shrink-0">
              {[
                { key: "home" as const, icon: MessageCircle, label: "Home" },
                { key: "chat" as const, icon: Bot, label: "Chat AI" },
              ].map((tab) => {
                const Icon = tab.icon;
                return (
                  <button
                    key={tab.key}
                    onClick={() => setActiveTab(tab.key)}
                    className={`flex-1 flex flex-col items-center gap-0.5 py-2.5 text-[10px] font-medium transition-colors ${
                      activeTab === tab.key ? "text-primary" : "text-muted hover:text-white"
                    }`}
                  >
                    <Icon size={16} />
                    {tab.label}
                  </button>
                );
              })}
            </div>
          </motion.div>
        )}
      </AnimatePresence>
    </>
  );
}
