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

export default function AIAgentsShowcase({ lang }: { lang: Lang }) {
  // Define agents array inside component to ensure it's always available
  const agents = [
    {
      icon: "🤖",
      nameEn: "FAQ Assistant",
      nameAr: "مساعد الأسئلة",
      roleEn: "Instant Answers 24/7",
      roleAr: "إجابات فورية 24/7",
      tasksEn: [
        "Answer common questions",
        "Provide service info",
        "Handle pricing inquiries",
        "Share working hours",
      ],
      tasksAr: [
        "الرد على الأسئلة الشائعة",
        "توفير معلومات الخدمات",
        "معالجة استفسارات الأسعار",
        "مشاركة ساعات العمل",
      ],
      colorFrom: "from-blue-500",
      colorTo: "to-cyan-500",
    },
    {
      icon: "📅",
      nameEn: "Booking Agent",
      nameAr: "وكيل الحجوزات",
      roleEn: "Smart Scheduling",
      roleAr: "جدولة ذكية",
      tasksEn: [
        "Check availability",
        "Book appointments",
        "Manage reschedules",
        "Send confirmations",
      ],
      tasksAr: [
        "التحقق من التوفر",
        "حجز المواعيد",
        "إدارة إعادة الجدولة",
        "إرسال التأكيدات",
      ],
      colorFrom: "from-green-500",
      colorTo: "to-emerald-500",
    },
    {
      icon: "📞",
      nameEn: "Voice Agent",
      nameAr: "الوكيل الصوتي",
      roleEn: "Natural Conversations",
      roleAr: "محادثات طبيعية",
      tasksEn: [
        "Make reminder calls",
        "Confirm appointments",
        "Follow up on visits",
        "Handle voice queries",
      ],
      tasksAr: [
        "مكالمات التذكير",
        "تأكيد المواعيد",
        "متابعة الزيارات",
        "معالجة الاستفسارات الصوتية",
      ],
      colorFrom: "from-purple-500",
      colorTo: "to-pink-500",
    },
    {
      icon: "💳",
      nameEn: "Payment Agent",
      nameAr: "وكيل المدفوعات",
      roleEn: "Secure Transactions",
      roleAr: "معاملات آمنة",
      tasksEn: [
        "Process deposits",
        "Send payment links",
        "Handle refunds",
        "Track payments",
      ],
      tasksAr: [
        "معالجة العربون",
        "إرسال روابط الدفع",
        "معالجة المبالغ المستردة",
        "تتبع المدفوعات",
      ],
      colorFrom: "from-orange-500",
      colorTo: "to-red-500",
    },
    {
      icon: "🧠",
      nameEn: "GLM 4.6 Assistant",
      nameAr: "مساعد GLM 4.6",
      roleEn: "Advanced AI Language Model",
      roleAr: "نموذج لغوي ذكي متقدم",
      tasksEn: [
        "Multilingual conversations",
        "Complex problem solving",
        "Content generation",
        "Advanced analytics",
      ],
      tasksAr: [
        "محادثات متعددة اللغات",
        "حل المشكلات المعقدة",
        "إنشاء المحتوى",
        "تحليلات متقدمة",
      ],
      colorFrom: "from-indigo-500",
      colorTo: "to-purple-500",
    },
  ];
  const isAr = lang === "ar";
  const [activeAgent, setActiveAgent] = useState(0);
  const [typingText, setTypingText] = useState("");
  const [isTyping] = useState(false); // setIsTyping removed - unused

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

    let messageIndex = 0;
    let charIndex = 0;

    const typeInterval = setInterval(() => {
      if (!messages || messages.length === 0) {
        return;
      }

      if (messageIndex >= messages.length) {
        messageIndex = 0;
        charIndex = 0;
        setTypingText("");
      } else {
        const currentMessage = messages[messageIndex];
        if (currentMessage && charIndex < currentMessage.length) {
          const char = currentMessage[charIndex];
          if (char !== undefined) {
            setTypingText((prev) => prev + char);
            charIndex++;
          }
        } else {
          setTimeout(() => {
            setTypingText("");
            messageIndex++;
            charIndex = 0;
          }, 1500);
        }
      }
    }, 50);

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

  return (
    <section className="py-20 px-4 bg-gradient-to-b from-white to-slate-50 dark:from-slate-900 dark:to-slate-800">
      <div className="max-w-7xl mx-auto">
        {/* Header */}
        <div className="text-center mb-12">
          <div className="inline-flex items-center gap-2 bg-purple-100 dark:bg-purple-900/30 text-purple-800 dark:text-purple-300 px-4 py-2 rounded-full mb-4">
            <span>🤖</span>
            <span className="font-semibold">
              {isAr ? "وكلاء الذكاء الاصطناعي" : "AI Agents"}
            </span>
          </div>
          <h2 className="text-4xl md:text-5xl font-bold text-brand-ink dark:text-white mb-4">
            {isAr ? (
              <>
                <span className="block">فريقك الرقمي الذي</span>
                <span className="block bg-gradient-to-r from-purple-600 to-pink-600 bg-clip-text text-transparent">
                  لا ينام أبداً
                </span>
              </>
            ) : (
              <>
                <span className="block">Your Digital Team That</span>
                <span className="block bg-gradient-to-r from-purple-600 to-pink-600 bg-clip-text text-transparent">
                  Never Sleeps
                </span>
              </>
            )}
          </h2>
          <p className="text-xl text-slate-600 dark:text-slate-300 max-w-3xl mx-auto">
            {isAr
              ? "وكلاء ذكاء اصطناعي متخصصون يتعاملون مع كل شيء من الأسئلة إلى الحجوزات إلى المدفوعات"
              : "Specialized AI agents that handle everything from questions to bookings to payments"}
          </p>
        </div>

        <div className="grid lg:grid-cols-2 gap-12 items-start">
          {/* Left: Agent Cards */}
          <div className="space-y-4">
            {agents.map((agent, index) => (
              <div
                key={index}
                className={`relative p-6 rounded-xl cursor-pointer transition-all duration-500 ${
                  activeAgent === index
                    ? "bg-white dark:bg-slate-800 shadow-2xl scale-105 border-2 border-purple-500"
                    : "bg-white/50 dark:bg-slate-800/50 hover:shadow-lg"
                }`}
                onClick={() => setActiveAgent(index)}
              >
                <div className="flex items-start gap-4">
                  <div
                    className={`w-14 h-14 rounded-xl bg-gradient-to-br ${agent.colorFrom} ${agent.colorTo} flex items-center justify-center text-2xl text-white shadow-lg ${
                      activeAgent === index ? "animate-pulse" : ""
                    }`}
                  >
                    {agent.icon}
                  </div>
                  <div className="flex-1">
                    <h3 className="text-lg font-bold text-brand-ink dark:text-white mb-1">
                      {isAr ? agent.nameAr : agent.nameEn}
                    </h3>
                    <p className="text-sm text-slate-500 dark:text-slate-400 mb-3">
                      {isAr ? agent.roleAr : agent.roleEn}
                    </p>
                    <div className="grid grid-cols-2 gap-2">
                      {(isAr ? agent.tasksAr : agent.tasksEn).map((task, i) => (
                        <div
                          key={i}
                          className={`text-xs px-3 py-1 rounded-full transition-all duration-300 ${
                            activeAgent === index
                              ? "bg-purple-100 dark:bg-purple-900/30 text-purple-700 dark:text-purple-300"
                              : "bg-slate-100 dark:bg-slate-700 text-slate-600 dark:text-slate-400"
                          }`}
                          style={{
                            animationDelay: `${i * 100}ms`,
                          }}
                        >
                          {task}
                        </div>
                      ))}
                    </div>
                  </div>
                </div>
                {activeAgent === index && (
                  <div className="absolute inset-0 bg-gradient-to-r from-purple-500/10 to-pink-500/10 rounded-xl animate-pulse" />
                )}
              </div>
            ))}
          </div>

          {/* Right: Interactive Demo */}
          <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-6 h-64 bg-slate-50 dark:bg-slate-900">
                {/* Typing Indicator */}
                <div className="flex items-end gap-2">
                  <div className="w-8 h-8 bg-gradient-to-br from-purple-500 to-pink-500 rounded-full flex items-center justify-center">
                    <span className="text-white text-sm">
                      {agents[activeAgent] ? agents[activeAgent].icon : "🤖"}
                    </span>
                  </div>
                  <div className="bg-white dark:bg-slate-800 rounded-2xl rounded-bl-none px-4 py-3 max-w-xs">
                    <p className="text-sm text-slate-700 dark:text-slate-300">
                      {typingText}
                      {isTyping && <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>
        </div>
      </div>
    </section>
  );
}
