"use client";
import { useState, useEffect } from "react";
import { type Lang } from "@/lib/config";
import { agents } from "./AgentData";

interface AgentChatDemoProps {
  lang: Lang;
  activeAgent: number;
}

export default function AgentChatDemo({
  lang,
  activeAgent,
}: AgentChatDemoProps) {
  const isAr = lang === "ar";

  const [chatMessages, setChatMessages] = useState<
    Array<{ text: string; isBot: boolean }>
  >([]);
  const [currentTypingText, setCurrentTypingText] = useState("");
  const [isCurrentBot, setIsCurrentBot] = useState(true);

  useEffect(() => {
    const conversation = isAr
      ? [
          { text: "مرحباً! كيف يمكنني مساعدتك اليوم؟", isBot: true },
          { text: "أريد حجز موعد", isBot: false },
          { text: "بالتأكيد! دعني أتحقق من المواعيد المتاحة...", isBot: true },
        ]
      : [
          { text: "Hello! How can I help you today?", isBot: true },
          { text: "I want to book an appointment", isBot: false },
          { text: "Sure! Let me check available slots...", isBot: true },
        ];

    let messageIndex = 0;
    let charIndex = 0;
    let isPaused = false;

    // Reset on agent change
    setChatMessages([]);
    setCurrentTypingText("");

    const typeInterval = setInterval(() => {
      if (isPaused) return;

      // Restart conversation after all messages
      if (messageIndex >= conversation.length) {
        isPaused = true;
        setTimeout(() => {
          messageIndex = 0;
          charIndex = 0;
          setChatMessages([]);
          setCurrentTypingText("");
          isPaused = false;
        }, 3000);
        return;
      }

      const currentMessage = conversation[messageIndex];
      if (!currentMessage) return;

      if (charIndex === 0) {
        // Starting a new message - set which type it is
        setIsCurrentBot(currentMessage.isBot);
      }

      if (charIndex < currentMessage.text.length) {
        // Type next character
        setCurrentTypingText(currentMessage.text.slice(0, charIndex + 1));
        charIndex++;
      } else {
        // Message complete - add to chat and move to next
        isPaused = true;
        setChatMessages((prev) => [
          ...prev,
          { text: currentMessage.text, isBot: currentMessage.isBot },
        ]);
        setCurrentTypingText("");

        setTimeout(() => {
          messageIndex++;
          charIndex = 0;
          isPaused = false;
        }, 1000);
      }
    }, 100);

    return () => clearInterval(typeInterval);
  }, [isAr, activeAgent]);

  return (
    <div className="sticky top-20">
      {/* Chat Interface */}
      <div className="bg-white dark:bg-slate-800 rounded-2xl shadow-2xl overflow-hidden">
        <div className="bg-gradient-to-r from-purple-600 to-pink-600 p-4 text-white">
          <div className="flex items-center justify-between">
            <div className="flex items-center gap-3">
              <div className="w-10 h-10 bg-white/20 rounded-full flex items-center justify-center">
                {agents[activeAgent] ? agents[activeAgent].icon : "🤖"}
              </div>
              <div>
                <p className="font-semibold">
                  {agents[activeAgent]
                    ? isAr
                      ? agents[activeAgent].nameAr
                      : agents[activeAgent].nameEn
                    : isAr
                      ? "مساعد ذكي"
                      : "AI Assistant"}
                </p>
                <p className="text-xs opacity-90">
                  {isAr ? "متصل الآن" : "Online Now"}
                </p>
              </div>
            </div>
            <div className="flex gap-2">
              <div className="w-2 h-2 bg-green-400 rounded-full animate-pulse" />
              <div className="w-2 h-2 bg-green-400 rounded-full animate-pulse delay-1000" />
              <div className="w-2 h-2 bg-green-400 rounded-full animate-pulse delay-2000" />
            </div>
          </div>
        </div>

        <div className="p-4 h-64 bg-slate-50 dark:bg-slate-900 overflow-y-auto flex flex-col gap-3">
          {/* Completed messages */}
          {chatMessages.map((msg, idx) => (
            <div
              key={idx}
              className={`flex items-end gap-2 ${msg.isBot ? "" : "flex-row-reverse"}`}
            >
              {msg.isBot && (
                <div className="w-8 h-8 bg-gradient-to-br from-purple-500 to-pink-500 rounded-full flex items-center justify-center flex-shrink-0">
                  <span className="text-white text-sm">
                    {agents[activeAgent]?.icon || "🤖"}
                  </span>
                </div>
              )}
              <div
                className={`px-4 py-2 max-w-[80%] ${
                  msg.isBot
                    ? "bg-white dark:bg-slate-800 rounded-2xl rounded-bl-none"
                    : "bg-purple-600 text-white rounded-2xl rounded-br-none"
                }`}
              >
                <p
                  className={`text-sm ${msg.isBot ? "text-slate-700 dark:text-slate-300" : "text-white"}`}
                >
                  {msg.text}
                </p>
              </div>
            </div>
          ))}

          {/* Currently typing message */}
          {currentTypingText && (
            <div
              className={`flex items-end gap-2 ${isCurrentBot ? "" : "flex-row-reverse"}`}
            >
              {isCurrentBot && (
                <div className="w-8 h-8 bg-gradient-to-br from-purple-500 to-pink-500 rounded-full flex items-center justify-center flex-shrink-0">
                  <span className="text-white text-sm">
                    {agents[activeAgent]?.icon || "🤖"}
                  </span>
                </div>
              )}
              <div
                className={`px-4 py-2 max-w-[80%] ${
                  isCurrentBot
                    ? "bg-white dark:bg-slate-800 rounded-2xl rounded-bl-none"
                    : "bg-purple-600 text-white rounded-2xl rounded-br-none"
                }`}
              >
                <p
                  className={`text-sm ${isCurrentBot ? "text-slate-700 dark:text-slate-300" : "text-white"}`}
                >
                  {currentTypingText}
                  <span className="animate-pulse">|</span>
                </p>
              </div>
            </div>
          )}
        </div>

        {/* Quick Actions */}
        <div className="p-4 bg-white dark:bg-slate-800 border-t dark:border-slate-700">
          <p className="text-xs text-slate-500 dark:text-slate-400 mb-3">
            {isAr ? "إجراءات سريعة:" : "Quick Actions:"}
          </p>
          <div className="grid grid-cols-2 gap-2">
            {[
              {
                icon: "📅",
                text: isAr ? "حجز موعد" : "Book Appointment",
              },
              { icon: "❓", text: isAr ? "سؤال" : "Ask Question" },
              { icon: "💳", text: isAr ? "دفع عربون" : "Pay Deposit" },
              { icon: "📞", text: isAr ? "طلب مكالمة" : "Request Call" },
            ].map((action, i) => (
              <button
                key={i}
                className="flex items-center gap-2 px-3 py-2 bg-slate-100 dark:bg-slate-700 rounded-lg hover:bg-slate-200 dark:hover:bg-slate-600 transition-colors text-sm"
              >
                <span>{action.icon}</span>
                <span className="text-slate-700 dark:text-slate-300">
                  {action.text}
                </span>
              </button>
            ))}
          </div>
        </div>
      </div>

      {/* Benefits */}
      <div className="mt-6 grid grid-cols-3 gap-3">
        {[
          { value: "24/7", label: isAr ? "متاح دائماً" : "Always On" },
          { value: "<10s", label: isAr ? "وقت الرد" : "Response" },
          { value: "∞", label: isAr ? "المحادثات" : "Conversations" },
        ].map((stat, i) => (
          <div
            key={i}
            className="text-center p-3 bg-gradient-to-br from-purple-50 to-pink-50 dark:from-purple-900/20 dark:to-pink-900/20 rounded-xl"
          >
            <div className="text-xl font-bold bg-gradient-to-r from-purple-600 to-pink-600 bg-clip-text text-transparent">
              {stat.value}
            </div>
            <div className="text-xs text-slate-600 dark:text-slate-400">
              {stat.label}
            </div>
          </div>
        ))}
      </div>
    </div>
  );
}
