"use client";

import { useState, useRef, useEffect } from "react";
import { motion, AnimatePresence } from "framer-motion";
import { Send, Bot, User, Sparkles } from "lucide-react";
import type { Locale } from "@/lib/i18n";

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

interface LiveChatProps {
  locale?: Locale;
  className?: string;
}

const demoConversations = {
  en: [
    { role: "assistant" as const, content: "Hello! I'm Sarah, your AI Sales Agent. I've been analyzing your leads overnight. Want to see what I found?", delay: 1000 },
    { role: "user" as const, content: "Yes, show me the results!", delay: 0 },
    { role: "assistant" as const, content: "Great! I qualified 47 new leads and closed 3 deals while you were sleeping. Total revenue: $12,400. Here's the breakdown:", delay: 1500 },
    { role: "assistant" as const, content: "🎯 15 enterprise leads qualified\n💰 3 deals closed ($8,400)\n📧 32 follow-ups scheduled\n\nReady for me to start working on today's leads?", delay: 2000 }
  ],
  ar: [
    { role: "assistant" as const, content: "مرحباً! أنا سارة، وكيلة المبيعات AI. لقد حللت عملائك المحتملين طوال الليل. هل تريد رؤية ما وجدت؟", delay: 1000 },
    { role: "user" as const, content: "نعم، أرني النتائج!", delay: 0 },
    { role: "assistant" as const, content: "ممتاز! مؤهلت 47 عميل محتمل جديد وأغلقت 3 صفقات أثناء نومك. إجمالي الإيرادات: $12,400. إليك التفاصيل:", delay: 1500 },
    { role: "assistant" as const, content: "🎯 15 عميل مؤهل من الشركات\n💰 3 صفقات مغلقة ($8,400)\n📧 32 متابعة مجدولة\n\nهل تريد مني البدء في العمل على عملاء اليوم المحتملين؟", delay: 2000 }
  ]
};

export function LiveChat({ locale = "en", className = "" }: LiveChatProps) {
  const [messages, setMessages] = useState<Message[]>([]);
  const [isTyping, setIsTyping] = useState(false);
  const [currentStep, setCurrentStep] = useState(0);
  const messagesEndRef = useRef<HTMLDivElement>(null);
  const isRTL = locale === "ar";

  const conversation = demoConversations[locale];

  useEffect(() => {
    if (currentStep < conversation.length) {
      const currentMsg = conversation[currentStep];

      if (currentMsg.role === "assistant") {
        setIsTyping(true);
        const typingDelay = currentMsg.delay || 1000;

        setTimeout(() => {
          setIsTyping(false);
          const newMessage: Message = {
            id: Date.now().toString(),
            role: currentMsg.role,
            content: currentMsg.content,
            timestamp: new Date()
          };
          setMessages(prev => [...prev, newMessage]);
          setCurrentStep(prev => prev + 1);
        }, typingDelay);
      }
    }
  }, [currentStep, conversation, locale]);

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

  const handleSendMessage = (content: string) => {
    const userMessage: Message = {
      id: Date.now().toString(),
      role: "user",
      content,
      timestamp: new Date()
    };
    setMessages(prev => [...prev, userMessage]);
    setCurrentStep(prev => prev + 1);
  };

  return (
    <div className={`bg-obsidian/80 backdrop-blur-xl border border-white/10 rounded-2xl overflow-hidden ${className}`} dir={isRTL ? "rtl" : "ltr"}>
      {/* Header */}
      <div className="bg-gradient-to-r from-electric-cyan/20 to-soft-emerald/20 border-b border-white/10 px-4 py-3">
        <div className="flex items-center gap-3">
          <div className="relative">
            <div className="w-10 h-10 rounded-full bg-gradient-to-r from-electric-cyan to-soft-emerald flex items-center justify-center">
              <Bot className="w-5 h-5 text-void-black" />
            </div>
            <div className="absolute -bottom-0.5 -right-0.5 w-3 h-3 bg-green-500 rounded-full border-2 border-obsidian" />
          </div>
          <div className="flex-1">
            <div className="font-semibold text-warm-white text-sm">
              {locale === "en" ? "AI Sales Agent" : "وكيل المبيعات AI"}
            </div>
            <div className="text-xs text-muted-white flex items-center gap-1">
              <Sparkles className="w-3 h-3 text-soft-emerald" />
              {locale === "en" ? "Active Now" : "نشط الآن"}
            </div>
          </div>
        </div>
      </div>

      {/* Messages */}
      <div className="h-56 md:h-72 lg:h-80 overflow-y-auto p-4 space-y-4">
        <AnimatePresence>
          {messages.map((message) => (
            <motion.div
              key={message.id}
              initial={{ opacity: 0, y: 10 }}
              animate={{ opacity: 1, y: 0 }}
              exit={{ opacity: 0, scale: 0.95 }}
              transition={{ duration: 0.3 }}
              className={`flex ${message.role === "user" ? "justify-end" : "justify-start"}`}
            >
              <div className={`flex gap-3 max-w-[85%] ${message.role === "user" ? "flex-row-reverse" : ""}`}>
                {message.role === "assistant" && (
                  <div className="w-8 h-8 rounded-full bg-gradient-to-r from-electric-cyan to-soft-emerald flex items-center justify-center flex-shrink-0">
                    <Bot className="w-4 h-4 text-void-black" />
                  </div>
                )}
                <div className={`px-4 py-2 rounded-2xl ${
                  message.role === "user"
                    ? "bg-electric-cyan text-void-black"
                    : "bg-white/5 border border-white/10 text-warm-white"
                }`}>
                  <p className="text-sm whitespace-pre-line">{message.content}</p>
                </div>
                {message.role === "user" && (
                  <div className="w-8 h-8 rounded-full bg-graphite flex items-center justify-center flex-shrink-0">
                    <User className="w-4 h-4 text-muted-white" />
                  </div>
                )}
              </div>
            </motion.div>
          ))}
        </AnimatePresence>

        {/* Typing Indicator */}
        {isTyping && (
          <motion.div
            initial={{ opacity: 0, y: 10 }}
            animate={{ opacity: 1, y: 0 }}
            className="flex justify-start"
          >
            <div className="flex gap-3">
              <div className="w-8 h-8 rounded-full bg-gradient-to-r from-electric-cyan to-soft-emerald flex items-center justify-center">
                <Bot className="w-4 h-4 text-void-black" />
              </div>
              <div className="bg-white/5 border border-white/10 px-4 py-3 rounded-2xl">
                <div className="flex gap-1">
                  <div className="w-2 h-2 bg-electric-cyan rounded-full animate-bounce" style={{ animationDelay: "0ms" }} />
                  <div className="w-2 h-2 bg-electric-cyan rounded-full animate-bounce" style={{ animationDelay: "150ms" }} />
                  <div className="w-2 h-2 bg-electric-cyan rounded-full animate-bounce" style={{ animationDelay: "300ms" }} />
                </div>
              </div>
            </div>
          </motion.div>
        )}
        <div ref={messagesEndRef} />
      </div>

      {/* Input */}
      {currentStep >= conversation.length - 1 && (
        <motion.div
          initial={{ opacity: 0, y: 20 }}
          animate={{ opacity: 1, y: 0 }}
          className="p-4 border-t border-white/10"
        >
          <button
            onClick={() => {
              const responseMsg = locale === "en"
                ? "Yes, let's get started!"
                : "نعم، لنبدأ!";
              handleSendMessage(responseMsg);
            }}
            className="w-full bg-gradient-to-r from-electric-cyan to-soft-emerald text-void-black font-semibold py-3 px-4 rounded-xl hover:opacity-90 transition-opacity flex items-center justify-center gap-2"
          >
            <span>{locale === "en" ? "Try AI Agent Demo" : "جرب وكيل AI"}</span>
            <Send className="w-4 h-4" />
          </button>
        </motion.div>
      )}
    </div>
  );
}
