"use client";

import { useState, useRef, useEffect } from "react";
import { motion, AnimatePresence } from "framer-motion";
import { Send, Bot, User, Sparkles, ArrowLeft, RotateCcw } from "lucide-react";
import { aiChatApi } from "@/lib/api";
import { useCartStore } from "@/lib/store";
import BottomNav from "@/components/menu/BottomNav";
import Link from "next/link";

interface Message {
  role: "user" | "assistant";
  message: string;
  timestamp: Date;
}

export default function AIGarsonPage() {
  const [messages, setMessages] = useState<Message[]>([
    {
      role: "assistant",
      message: "Merhaba! 👋 Ben AI Garsonunuz. Size menümüzden önerilerde bulunabilirim. Ne arzu edersiniz?",
      timestamp: new Date(),
    },
  ]);
  const [input, setInput] = useState("");
  const [isTyping, setIsTyping] = useState(false);
  const [sessionId, setSessionId] = useState<string>("");
  const messagesEndRef = useRef<HTMLDivElement>(null);
  const inputRef = useRef<HTMLInputElement>(null);
  const tableNumber = useCartStore((s) => s.tableNumber);
  const tableToken = useCartStore((s) => s.tableToken);

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

  const sendMessage = async () => {
    if (!input.trim() || isTyping) return;

    if (!tableToken) {
      setMessages((prev) => [
        ...prev,
        { role: "user", message: input.trim(), timestamp: new Date() },
        { role: "assistant", message: "Lütfen sipariş vermek veya benimle konuşmak için masadaki QR kodu okutunuz.", timestamp: new Date() },
      ]);
      setInput("");
      return;
    }

    const userMsg: Message = { role: "user", message: input.trim(), timestamp: new Date() };
    setMessages((prev) => [...prev, userMsg]);
    setInput("");
    setIsTyping(true);

    try {
      const res = await aiChatApi.sendMessage({
        message: userMsg.message,
        history: messages.map((m) => ({ role: m.role, message: m.message })),
        table_number: tableNumber,
        token: tableToken,
        session_id: sessionId || undefined,
      });

      if (res.data?.session_id) setSessionId(res.data.session_id);

      const aiMsg: Message = {
        role: "assistant",
        message: res.data?.message || "Üzgünüm, yanıt oluşturamadım.",
        timestamp: new Date(),
      };
      setMessages((prev) => [...prev, aiMsg]);
    } catch (err: any) {
      let errorMsg = "Bir hata oluştu. Lütfen tekrar deneyin.";
      
      if (err.message) {
        // Backend'den gelen hata mesajını doğrudan göster
        if (err.message.includes("Erişim reddedildi") || err.message.includes("Geçersiz QR")) {
          errorMsg = "⚠️ Lütfen masadaki QR kodu okutunuz.";
        } else if (err.message.includes("limit") || err.message.includes("fazla istek")) {
          errorMsg = `⚠️ ${err.message}`;
        } else if (err.message.includes("Oturum") || err.message.includes("giriş")) {
          errorMsg = "Bir hata oluştu. Lütfen tekrar deneyin.";
        } else {
          errorMsg = err.message;
        }
      }
      
      setMessages((prev) => [
        ...prev,
        { role: "assistant", message: errorMsg, timestamp: new Date() },
      ]);
    } finally {
      setIsTyping(false);
    }
  };

  const quickQuestions = [
    "Bugün ne önerirsin? 🤔",
    "En popüler yemekler hangileri? ⭐",
    "Tatlı olarak ne var? 🍰",
    "Hafif bir şey yemek istiyorum 🥗",
  ];

  const resetChat = () => {
    setMessages([
      { role: "assistant", message: "Merhaba! 👋 Yeni bir sohbet başlattınız. Size nasıl yardımcı olabilirim?", timestamp: new Date() },
    ]);
    setSessionId("");
  };

  return (
    <div className="min-h-screen flex flex-col pb-16">
      {/* Header */}
      <div className="glass border-b border-border/30 sticky top-0 z-40">
        <div className="max-w-lg mx-auto px-4 py-3 flex items-center gap-3">
          <Link href="/" className="w-8 h-8 rounded-full bg-muted flex items-center justify-center">
            <ArrowLeft className="w-4 h-4" />
          </Link>
          <div className="flex items-center gap-2 flex-1">
            <div className="relative">
              <div className="w-9 h-9 rounded-full bg-gradient-to-br from-primary to-emerald flex items-center justify-center">
                <Bot className="w-5 h-5 text-white" />
              </div>
              <div className="absolute -bottom-0.5 -right-0.5 w-3 h-3 bg-emerald rounded-full border-2 border-background" />
            </div>
            <div>
              <p className="text-sm font-bold">AI Garson</p>
              <p className="text-[10px] text-emerald font-medium">Çevrimiçi</p>
            </div>
          </div>
          <button onClick={resetChat} className="w-8 h-8 rounded-full bg-muted flex items-center justify-center hover:bg-accent transition-colors">
            <RotateCcw className="w-4 h-4" />
          </button>
        </div>
      </div>

      {/* Background Effects */}
      <div className="fixed inset-0 pointer-events-none">
        <div className="absolute top-1/4 left-0 w-64 h-64 bg-primary/5 rounded-full blur-3xl" />
        <div className="absolute bottom-1/4 right-0 w-48 h-48 bg-emerald/5 rounded-full blur-3xl" />
      </div>

      {/* Messages */}
      <div className="flex-1 overflow-y-auto px-4 py-4 max-w-lg mx-auto w-full">
        <AnimatePresence>
          {messages.map((msg, idx) => (
            <motion.div
              key={idx}
              initial={{ opacity: 0, y: 15, scale: 0.95 }}
              animate={{ opacity: 1, y: 0, scale: 1 }}
              transition={{ duration: 0.3, ease: "easeOut" }}
              className={`flex gap-2 mb-4 ${msg.role === "user" ? "justify-end" : "justify-start"}`}
            >
              {msg.role === "assistant" && (
                <div className="w-7 h-7 rounded-full bg-gradient-to-br from-primary to-emerald flex items-center justify-center flex-shrink-0 mt-1">
                  <Bot className="w-4 h-4 text-white" />
                </div>
              )}

              <div
                className={`max-w-[80%] px-4 py-3 rounded-2xl text-sm leading-relaxed ${
                  msg.role === "user"
                    ? "bg-primary text-primary-foreground rounded-br-sm"
                    : "bg-card border border-border/50 rounded-bl-sm"
                }`}
              >
                <p className="whitespace-pre-wrap">{msg.message}</p>
                <p className={`text-[10px] mt-1 ${msg.role === "user" ? "text-primary-foreground/60" : "text-muted-foreground"}`}>
                  {msg.timestamp.toLocaleTimeString("tr-TR", { hour: "2-digit", minute: "2-digit" })}
                </p>
              </div>

              {msg.role === "user" && (
                <div className="w-7 h-7 rounded-full bg-muted flex items-center justify-center flex-shrink-0 mt-1">
                  <User className="w-4 h-4" />
                </div>
              )}
            </motion.div>
          ))}
        </AnimatePresence>

        {/* Typing Indicator */}
        {isTyping && (
          <motion.div
            initial={{ opacity: 0, y: 10 }}
            animate={{ opacity: 1, y: 0 }}
            className="flex gap-2 mb-4"
          >
            <div className="w-7 h-7 rounded-full bg-gradient-to-br from-primary to-emerald flex items-center justify-center flex-shrink-0">
              <Bot className="w-4 h-4 text-white" />
            </div>
            <div className="bg-card border border-border/50 rounded-2xl rounded-bl-sm px-4 py-3 animate-glow-pulse">
              <div className="flex items-center gap-1.5">
                <span className="typing-dot w-2 h-2 bg-primary/70 rounded-full inline-block" />
                <span className="typing-dot w-2 h-2 bg-primary/70 rounded-full inline-block" />
                <span className="typing-dot w-2 h-2 bg-primary/70 rounded-full inline-block" />
              </div>
            </div>
          </motion.div>
        )}

        <div ref={messagesEndRef} />

        {/* Quick Questions */}
        {messages.length <= 1 && (
          <motion.div
            initial={{ opacity: 0, y: 20 }}
            animate={{ opacity: 1, y: 0 }}
            transition={{ delay: 0.3 }}
            className="mt-4"
          >
            <p className="text-xs text-muted-foreground mb-2 flex items-center gap-1">
              <Sparkles className="w-3 h-3" /> Hızlı sorular
            </p>
            <div className="flex flex-wrap gap-2">
              {quickQuestions.map((q, i) => (
                <motion.button
                  key={i}
                  whileTap={{ scale: 0.95 }}
                  onClick={() => { setInput(q); setTimeout(() => inputRef.current?.focus(), 100); }}
                  className="bg-card border border-border/50 rounded-full px-3 py-2 text-xs hover:border-primary/30 hover:bg-primary/5 transition-all"
                >
                  {q}
                </motion.button>
              ))}
            </div>
          </motion.div>
        )}
      </div>

      {/* Input */}
      <div className="glass border-t border-border/30 px-4 py-3 mb-16">
        <div className="max-w-lg mx-auto flex items-center gap-2">
          <input
            ref={inputRef}
            type="text"
            value={input}
            onChange={(e) => setInput(e.target.value)}
            onKeyDown={(e) => e.key === "Enter" && sendMessage()}
            placeholder="AI Garson'a bir şey sorun..."
            disabled={isTyping}
            className="flex-1 bg-muted/50 border border-border/50 rounded-xl py-3 px-4 text-sm focus:outline-none focus:ring-2 focus:ring-primary/30 disabled:opacity-50 transition-all"
          />
          <motion.button
            whileTap={{ scale: 0.9 }}
            onClick={sendMessage}
            disabled={!input.trim() || isTyping}
            className="w-11 h-11 rounded-xl bg-gradient-to-br from-primary to-amber flex items-center justify-center shadow-lg shadow-primary/25 disabled:opacity-50 transition-opacity"
          >
            <Send className="w-4 h-4 text-primary-foreground" />
          </motion.button>
        </div>
      </div>

      <BottomNav />
    </div>
  );
}
