"use client";

import { useState } from "react";
import { useConversation } from "@elevenlabs/react";
import classNames from "classnames";
import type { Lang } from "@/lib/config";

interface AIVoiceAgentCTAProps {
  lang: Lang;
}

export default function AIVoiceAgentCTA({ lang }: AIVoiceAgentCTAProps) {
  const [isWidgetVisible, setIsWidgetVisible] = useState(false);
  const isAr = lang === "ar";

  const conversation = useConversation({
    onConnect: () => console.log("Voice agent connected"),
    onDisconnect: () => {
      console.log("Voice agent disconnected");
      setIsWidgetVisible(false);
    },
    onError: (error) => console.error("Voice agent error:", error),
  });

  const handleStartConversation = async () => {
    try {
      // Request microphone permission first
      await navigator.mediaDevices.getUserMedia({ audio: true });

      // Show the widget
      setIsWidgetVisible(true);

      // Start the conversation with auto-call
      await conversation.startSession({
        agentId: "agent_1901kankm2vreyba3t77q3he8210",
        connectionType: "webrtc", // Use WebRTC for better quality
      });
    } catch (error) {
      console.error("Failed to start conversation:", error);
      alert(
        isAr
          ? "فشل بدء المحادثة. يرجى السماح بالوصول إلى الميكروفون."
          : "Failed to start conversation. Please allow microphone access.",
      );
      setIsWidgetVisible(false);
    }
  };

  const handleEndConversation = async () => {
    await conversation.endSession();
    setIsWidgetVisible(false);
  };

  return (
    <>
      <section className="relative overflow-hidden bg-gradient-to-br from-brand-green to-emerald-600 text-white">
        <div className="absolute inset-0 bg-[url('/grid.svg')] opacity-10" />

        <div className="relative mx-auto max-w-6xl px-4 py-20">
          <div className="text-center">
            {/* Badge */}
            <div className="mb-6 inline-flex items-center gap-2 rounded-full bg-white/20 px-4 py-2 backdrop-blur">
              <span className="text-2xl">🎙️</span>
              <span className="text-sm font-semibold">
                {isAr ? "تقنية الذكاء الاصطناعي الصوتي" : "AI Voice Technology"}
              </span>
            </div>

            {/* Heading */}
            <h2 className="text-3xl font-bold md:text-5xl">
              {isAr
                ? "جرّب مساعدنا الصوتي الذكي الآن"
                : "Try Our AI Voice Agent Now"}
            </h2>

            {/* Description */}
            <p className="mx-auto mt-6 max-w-2xl text-lg text-white/90">
              {isAr
                ? "تحدث مباشرةً مع مساعدنا الصوتي الذكي واكتشف كيف يمكن لموعدي أن يحول استفسارات عملائك إلى حجوزات مؤكدة بالعربية والإنجليزية"
                : "Speak directly with our AI voice agent and discover how Mawidi can transform your customer inquiries into confirmed bookings in Arabic and English"}
            </p>

            {/* CTA Button */}
            <div className="mt-10">
              <button
                onClick={handleStartConversation}
                disabled={conversation.status === "connected"}
                className={classNames(
                  "group relative inline-flex items-center gap-3 rounded-xl bg-white px-8 py-4 text-lg font-semibold text-brand-green shadow-2xl transition-all hover:scale-105 hover:shadow-xl",
                  "focus:outline-none focus:ring-4 focus:ring-white/50",
                  "disabled:opacity-50 disabled:cursor-not-allowed disabled:hover:scale-100",
                )}
              >
                <span className="text-2xl transition-transform group-hover:scale-110">
                  🎤
                </span>
                <span>
                  {conversation.status === "connected"
                    ? isAr
                      ? "متصل..."
                      : "Connected..."
                    : isAr
                      ? "ابدأ المحادثة الصوتية"
                      : "Start Voice Conversation"}
                </span>
                <svg
                  className={classNames(
                    "h-5 w-5 transition-transform group-hover:translate-x-1",
                    isAr && "rotate-180 group-hover:-translate-x-1",
                  )}
                  fill="none"
                  viewBox="0 0 24 24"
                  stroke="currentColor"
                >
                  <path
                    strokeLinecap="round"
                    strokeLinejoin="round"
                    strokeWidth={2}
                    d="M13 7l5 5m0 0l-5 5m5-5H6"
                  />
                </svg>
              </button>
            </div>

            {/* Features */}
            <div className="mt-12 grid gap-6 text-left md:grid-cols-3">
              {[
                {
                  icon: "🌐",
                  titleEn: "Bilingual Support",
                  titleAr: "دعم ثنائي اللغة",
                  descEn: "Seamlessly switches between Arabic and English",
                  descAr: "يتنقل بسلاسة بين العربية والإنجليزية",
                },
                {
                  icon: "⚡",
                  titleEn: "Instant Responses",
                  titleAr: "ردود فورية",
                  descEn: "Natural conversation with sub-second response time",
                  descAr: "محادثة طبيعية مع استجابة فورية",
                },
                {
                  icon: "🎯",
                  titleEn: "Smart Booking",
                  titleAr: "حجز ذكي",
                  descEn: "Understands context and guides to appointments",
                  descAr: "يفهم السياق ويوجه للمواعيد",
                },
              ].map((feature) => (
                <div
                  key={feature.titleEn}
                  className="rounded-xl bg-white/10 p-5 backdrop-blur transition-colors hover:bg-white/20"
                >
                  <div className="text-3xl">{feature.icon}</div>
                  <h3 className="mt-3 font-semibold">
                    {isAr ? feature.titleAr : feature.titleEn}
                  </h3>
                  <p className="mt-2 text-sm text-white/80">
                    {isAr ? feature.descAr : feature.descEn}
                  </p>
                </div>
              ))}
            </div>
          </div>
        </div>
      </section>

      {/* Voice Agent Modal - Only visible when active */}
      {isWidgetVisible && (
        <div className="fixed inset-0 z-50 flex items-center justify-center bg-black/50 backdrop-blur-sm">
          <div className="relative w-full max-w-md rounded-3xl bg-white p-8 shadow-2xl">
            {/* Header */}
            <div className="mb-6 text-center">
              <div className="mb-4 inline-flex h-16 w-16 items-center justify-center rounded-full bg-brand-green text-3xl">
                🎙️
              </div>
              <h3 className="text-2xl font-bold text-brand-ink">
                {isAr ? "المساعد الصوتي" : "Voice Assistant"}
              </h3>
              <p className="mt-2 text-sm text-neutral-600">
                {conversation.status === "connected" && conversation.isSpeaking
                  ? isAr
                    ? "يتحدث..."
                    : "Speaking..."
                  : conversation.status === "connected"
                    ? isAr
                      ? "يستمع..."
                      : "Listening..."
                    : isAr
                      ? "جاري الاتصال..."
                      : "Connecting..."}
              </p>
            </div>

            {/* Status Indicator */}
            <div className="mb-6 flex items-center justify-center gap-4">
              <div
                className={classNames(
                  "h-3 w-3 rounded-full",
                  conversation.status === "connected"
                    ? "animate-pulse bg-green-500"
                    : "bg-gray-400",
                )}
              />
              <span className="text-sm text-neutral-600">
                {conversation.status === "connected"
                  ? isAr
                    ? "متصل"
                    : "Connected"
                  : isAr
                    ? "جاري الاتصال"
                    : "Connecting"}
              </span>
            </div>

            {/* Visual Indicator */}
            {conversation.isSpeaking && (
              <div className="mb-6 flex items-center justify-center gap-2">
                {[1, 2, 3, 4, 5].map((i) => (
                  <div
                    key={i}
                    className="h-8 w-1 animate-pulse rounded-full bg-brand-green"
                    style={{
                      animationDelay: `${i * 100}ms`,
                      animationDuration: "600ms",
                    }}
                  />
                ))}
              </div>
            )}

            {/* Close Button */}
            <button
              onClick={handleEndConversation}
              className="w-full rounded-lg border border-red-500 px-6 py-3 text-red-500 hover:bg-red-50"
            >
              {isAr ? "إنهاء المكالمة" : "End Call"}
            </button>

            {/* Powered by */}
            <p className="mt-4 text-center text-xs text-neutral-400">
              Powered by ElevenLabs
            </p>
          </div>
        </div>
      )}
    </>
  );
}
