"use client";

import { useState, useEffect, useCallback } from "react";
import { useConversation } from "@elevenlabs/react";
import { UI, type Lang } from "@/lib/config";

interface VoiceAgentDemoProps {
  lang: Lang;
}

export default function VoiceAgentDemo({ lang }: VoiceAgentDemoProps) {
  const [isLoading, setIsLoading] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const [micPermissionGranted, setMicPermissionGranted] = useState(false);
  const [showVolumeControl, setShowVolumeControl] = useState(false);

  const t = UI[lang].t;
  const isAr = lang === "ar";

  // Initialize conversation hook with WebRTC
  const conversation = useConversation({
    // Language override based on current page language
    overrides: {
      agent: {
        language: lang === "ar" ? "ar" : "en",
      },
    },
    // Callbacks for handling conversation events
    onConnect: () => {
      console.log("Voice agent connected");
      setError(null);
    },
    onDisconnect: () => {
      console.log("Voice agent disconnected");
    },
    onError: (error) => {
      console.error("Voice agent error:", error);
      setError(isAr ? "حدث خطأ في الاتصال" : "Connection error occurred");
    },
    onMessage: (message) => {
      console.log("Message received:", message);
    },
  });

  // Request microphone permission
  const requestMicPermission = async () => {
    try {
      await navigator.mediaDevices.getUserMedia({ audio: true });
      setMicPermissionGranted(true);
      return true;
    } catch (err) {
      console.error("Microphone permission denied:", err);
      setError(
        isAr
          ? "يرجى السماح بالوصول إلى الميكروفون لاستخدام الوكيل الصوتي"
          : "Please allow microphone access to use the voice agent",
      );
      return false;
    }
  };

  // Fetch conversation token from backend
  const fetchConversationToken = async () => {
    setIsLoading(true);
    setError(null);

    try {
      const response = await fetch("/api/elevenlabs/conversation-token");

      if (!response.ok) {
        const errorData = await response.json();
        throw new Error(errorData.error || "Failed to get conversation token");
      }

      const data = await response.json();
      return data.token;
    } catch (err) {
      console.error("Error fetching conversation token:", err);
      setError(
        isAr
          ? "فشل الاتصال بخادم الوكيل الصوتي"
          : "Failed to connect to voice agent server",
      );
      return null;
    } finally {
      setIsLoading(false);
    }
  };

  // Start voice conversation
  const handleStartDemo = async () => {
    // First, request microphone permission
    const hasPermission = await requestMicPermission();
    if (!hasPermission) return;

    // Fetch conversation token
    const token = await fetchConversationToken();
    if (!token) return;

    // Start conversation with WebRTC
    try {
      await conversation.startSession({
        conversationToken: token,
        connectionType: "webrtc",
        // Optional: pass user ID for tracking
        // userId: 'demo-user-' + Date.now(),
      });
    } catch (err) {
      console.error("Failed to start conversation:", err);
      setError(
        isAr
          ? "فشل بدء المحادثة الصوتية"
          : "Failed to start voice conversation",
      );
    }
  };

  // End voice conversation
  const handleEndDemo = async () => {
    try {
      await conversation.endSession();
      setError(null);
    } catch (err) {
      console.error("Error ending conversation:", err);
    }
  };

  // Volume control handler
  const handleVolumeChange = useCallback(
    async (volume: number) => {
      try {
        await conversation.setVolume({ volume });
      } catch (err) {
        console.error("Error setting volume:", err);
      }
    },
    [conversation],
  );

  // Cleanup on unmount
  useEffect(() => {
    return () => {
      if (conversation.status === "connected") {
        conversation.endSession().catch(console.error);
      }
    };
  }, [conversation]);

  const isConnected = conversation.status === "connected";
  const isSpeaking = conversation.isSpeaking;

  return (
    <div className="relative">
      {/* Demo Container */}
      <div className="rounded-2xl border-2 border-purple-200 dark:border-purple-700/50 bg-gradient-to-br from-white to-purple-50/30 dark:from-slate-900 dark:to-purple-900/10 p-8 shadow-xl">
        {!isConnected ? (
          /* Initial State - Instructions */
          <div className="text-center space-y-6">
            <div className="w-24 h-24 mx-auto rounded-full bg-gradient-to-br from-purple-500 to-indigo-600 flex items-center justify-center shadow-2xl">
              <svg
                className="w-12 h-12 text-white"
                fill="none"
                viewBox="0 0 24 24"
                stroke="currentColor"
              >
                <path
                  strokeLinecap="round"
                  strokeLinejoin="round"
                  strokeWidth={2}
                  d="M19 11a7 7 0 01-7 7m0 0a7 7 0 01-7-7m7 7v4m0 0H8m4 0h4m-4-8a3 3 0 01-3-3V5a3 3 0 116 0v6a3 3 0 01-3 3z"
                />
              </svg>
            </div>

            <div className="space-y-3">
              <h3 className="text-2xl font-bold text-brand-ink dark:text-white">
                {isAr ? "جرب الوكيل الصوتي الآن" : "Try the Voice Agent Now"}
              </h3>
              <p className="text-gray-600 dark:text-gray-300 max-w-2xl mx-auto">
                {t.demoInstructions}
              </p>
            </div>

            {/* Error Message */}
            {error && (
              <div className="max-w-md mx-auto p-4 rounded-xl bg-red-50 dark:bg-red-900/20 border border-red-200 dark:border-red-700/30">
                <p className="text-sm text-red-800 dark:text-red-300">
                  <strong>{isAr ? "خطأ:" : "Error:"}</strong> {error}
                </p>
              </div>
            )}

            <div className="space-y-3">
              <button
                onClick={handleStartDemo}
                disabled={isLoading}
                className="group inline-flex items-center justify-center gap-3 rounded-xl bg-gradient-to-r from-purple-600 to-indigo-600 px-8 py-4 text-lg font-bold text-white shadow-xl transition-all hover:shadow-2xl hover:scale-105 disabled:opacity-50 disabled:cursor-not-allowed disabled:hover:scale-100"
              >
                {isLoading ? (
                  <>
                    <svg
                      className="animate-spin h-6 w-6"
                      xmlns="http://www.w3.org/2000/svg"
                      fill="none"
                      viewBox="0 0 24 24"
                    >
                      <circle
                        className="opacity-25"
                        cx="12"
                        cy="12"
                        r="10"
                        stroke="currentColor"
                        strokeWidth="4"
                      />
                      <path
                        className="opacity-75"
                        fill="currentColor"
                        d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"
                      />
                    </svg>
                    {isAr ? "جاري الاتصال..." : "Connecting..."}
                  </>
                ) : (
                  <>
                    <svg
                      className="w-6 h-6"
                      fill="currentColor"
                      viewBox="0 0 24 24"
                    >
                      <path d="M8 5v14l11-7z" />
                    </svg>
                    {t.demoButton}
                  </>
                )}
              </button>

              <div className="flex items-center justify-center gap-4 text-xs text-gray-500 dark:text-gray-400">
                <span className="flex items-center gap-1">
                  <span className="inline-block w-2 h-2 rounded-full bg-emerald-500 animate-pulse" />
                  {isAr ? "مباشر" : "Live"}
                </span>
                <span>•</span>
                <span>{isAr ? "عربي وإنجليزي" : "Arabic & English"}</span>
                <span>•</span>
                <span>{isAr ? "مجاني" : "Free"}</span>
              </div>
            </div>

            {/* Microphone Permission Notice */}
            {!micPermissionGranted && (
              <div className="mt-4 p-3 rounded-lg bg-yellow-50 dark:bg-yellow-900/20 border border-yellow-200 dark:border-yellow-700/30">
                <p className="text-xs text-yellow-800 dark:text-yellow-300">
                  <strong>🎤</strong>{" "}
                  {isAr
                    ? "ستحتاج إلى السماح بالوصول إلى الميكروفون عند بدء المحادثة"
                    : "You will need to allow microphone access when starting the conversation"}
                </p>
              </div>
            )}

            {/* Sample Questions */}
            <div className="mt-8 pt-6 border-t border-slate-200 dark:border-slate-700">
              <p className="text-sm font-semibold text-gray-700 dark:text-gray-300 mb-3">
                {isAr ? "جرب هذه الأسئلة:" : "Try asking:"}
              </p>
              <div className="flex flex-wrap gap-2 justify-center">
                {isAr ? (
                  <>
                    <span className="px-3 py-1.5 rounded-full bg-purple-100 dark:bg-purple-900/30 text-xs font-medium text-purple-700 dark:text-purple-400">
                      &ldquo;ما هي مواعيدكم المتاحة؟&rdquo;
                    </span>
                    <span className="px-3 py-1.5 rounded-full bg-purple-100 dark:bg-purple-900/30 text-xs font-medium text-purple-700 dark:text-purple-400">
                      &ldquo;أريد حجز موعد&rdquo;
                    </span>
                    <span className="px-3 py-1.5 rounded-full bg-purple-100 dark:bg-purple-900/30 text-xs font-medium text-purple-700 dark:text-purple-400">
                      &ldquo;كم تكلفة الاستشارة؟&rdquo;
                    </span>
                  </>
                ) : (
                  <>
                    <span className="px-3 py-1.5 rounded-full bg-purple-100 dark:bg-purple-900/30 text-xs font-medium text-purple-700 dark:text-purple-400">
                      &ldquo;What are your available times?&rdquo;
                    </span>
                    <span className="px-3 py-1.5 rounded-full bg-purple-100 dark:bg-purple-900/30 text-xs font-medium text-purple-700 dark:text-purple-400">
                      &ldquo;I want to book an appointment&rdquo;
                    </span>
                    <span className="px-3 py-1.5 rounded-full bg-purple-100 dark:bg-purple-900/30 text-xs font-medium text-purple-700 dark:text-purple-400">
                      &ldquo;How much does a consultation cost?&rdquo;
                    </span>
                  </>
                )}
              </div>
            </div>
          </div>
        ) : (
          /* Active State - Voice Agent Interface */
          <div className="space-y-6">
            {/* Connection Status Header */}
            <div className="flex items-center justify-between">
              <div className="flex items-center gap-3">
                <div className="relative">
                  <span className="inline-block w-3 h-3 rounded-full bg-emerald-500 animate-pulse" />
                  {isSpeaking && (
                    <span className="absolute inset-0 rounded-full bg-emerald-500 animate-ping" />
                  )}
                </div>
                <div className="text-left">
                  <span className="block text-sm font-semibold text-gray-700 dark:text-gray-300">
                    {isAr ? "الوكيل متصل" : "Agent Connected"}
                  </span>
                  <span className="block text-xs text-gray-500 dark:text-gray-400">
                    {isSpeaking
                      ? isAr
                        ? "🗣️ الوكيل يتحدث..."
                        : "🗣️ Agent speaking..."
                      : isAr
                        ? "👂 في وضع الاستماع"
                        : "👂 Listening mode"}
                  </span>
                </div>
              </div>

              <div className="flex items-center gap-2">
                {/* Volume Control Toggle */}
                <button
                  onClick={() => setShowVolumeControl(!showVolumeControl)}
                  className="p-2 rounded-lg hover:bg-purple-100 dark:hover:bg-purple-900/30 transition-colors"
                  title={isAr ? "التحكم بالصوت" : "Volume control"}
                >
                  <svg
                    className="w-5 h-5 text-gray-600 dark:text-gray-400"
                    fill="none"
                    viewBox="0 0 24 24"
                    stroke="currentColor"
                  >
                    <path
                      strokeLinecap="round"
                      strokeLinejoin="round"
                      strokeWidth={2}
                      d="M15.536 8.464a5 5 0 010 7.072m2.828-9.9a9 9 0 010 12.728M5.586 15H4a1 1 0 01-1-1v-4a1 1 0 011-1h1.586l4.707-4.707C10.923 3.663 12 4.109 12 5v14c0 .891-1.077 1.337-1.707.707L5.586 15z"
                    />
                  </svg>
                </button>

                {/* End Session Button */}
                <button
                  onClick={handleEndDemo}
                  className="px-4 py-2 rounded-lg text-sm font-medium text-red-600 dark:text-red-400 hover:bg-red-50 dark:hover:bg-red-900/20 transition-colors"
                >
                  {isAr ? "❌ إنهاء" : "❌ End Demo"}
                </button>
              </div>
            </div>

            {/* Volume Control Panel */}
            {showVolumeControl && (
              <div className="p-4 rounded-xl bg-purple-50 dark:bg-purple-900/20 border border-purple-200 dark:border-purple-700/30">
                <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
                  {isAr ? "🔊 مستوى الصوت" : "🔊 Volume Level"}
                </label>
                <input
                  type="range"
                  min="0"
                  max="1"
                  step="0.1"
                  defaultValue="0.8"
                  onChange={(e) =>
                    handleVolumeChange(parseFloat(e.target.value))
                  }
                  className="w-full h-2 bg-purple-200 dark:bg-purple-700 rounded-lg appearance-none cursor-pointer accent-purple-600"
                />
              </div>
            )}

            {/* Voice Visualization */}
            <div className="relative rounded-xl overflow-hidden bg-gradient-to-br from-slate-100 to-purple-100 dark:from-slate-800 dark:to-purple-900/20 p-8">
              <div className="flex flex-col items-center justify-center space-y-6">
                {/* Animated Microphone Icon */}
                <div
                  className={`w-24 h-24 rounded-full bg-gradient-to-br from-purple-500 to-indigo-600 flex items-center justify-center shadow-2xl transition-all ${
                    isSpeaking ? "animate-pulse scale-110" : "scale-100"
                  }`}
                >
                  <svg
                    className="w-12 h-12 text-white"
                    fill="none"
                    viewBox="0 0 24 24"
                    stroke="currentColor"
                  >
                    <path
                      strokeLinecap="round"
                      strokeLinejoin="round"
                      strokeWidth={2}
                      d="M19 11a7 7 0 01-7 7m0 0a7 7 0 01-7-7m7 7v4m0 0H8m4 0h4m-4-8a3 3 0 01-3-3V5a3 3 0 116 0v6a3 3 0 01-3 3z"
                    />
                  </svg>
                </div>

                {/* Status Text */}
                <div className="text-center space-y-2">
                  <p className="text-lg font-bold text-gray-800 dark:text-gray-200">
                    {isSpeaking
                      ? isAr
                        ? "الوكيل يتحدث الآن..."
                        : "Agent is speaking..."
                      : isAr
                        ? "تحدث الآن"
                        : "Speak now"}
                  </p>
                  <p className="text-sm text-gray-600 dark:text-gray-400">
                    {isAr
                      ? "اسأل عن المواعيد، الأسعار، أو احجز موعد"
                      : "Ask about appointments, pricing, or book a session"}
                  </p>
                </div>

                {/* Waveform Animation */}
                <div className="flex items-center gap-1 h-12">
                  {[...Array(20)].map((_, i) => (
                    <div
                      key={i}
                      className={`w-1 bg-purple-600 dark:bg-purple-400 rounded-full transition-all ${
                        isSpeaking ? "animate-pulse" : ""
                      }`}
                      style={{
                        height: isSpeaking
                          ? `${Math.random() * 40 + 10}px`
                          : "4px",
                        animationDelay: `${i * 0.1}s`,
                      }}
                    />
                  ))}
                </div>
              </div>
            </div>

            {/* Language Indicator */}
            <div className="flex items-center justify-center gap-4 text-xs text-gray-600 dark:text-gray-400 pt-2">
              <span className="flex items-center gap-1">
                🎤 {isAr ? "متصل بالميكروفون" : "Microphone active"}
              </span>
              <span>•</span>
              <span>
                🌐{" "}
                {isAr
                  ? "يتحدث العربية والإنجليزية"
                  : "Speaking Arabic & English"}
              </span>
            </div>
          </div>
        )}
      </div>

      {/* Instructions below demo */}
      {isConnected && (
        <div className="mt-4 p-4 rounded-xl bg-blue-50 dark:bg-blue-900/20 border border-blue-200 dark:border-blue-700/30">
          <p className="text-sm text-blue-800 dark:text-blue-300">
            <strong>{isAr ? "ملاحظة:" : "Note:"}</strong>{" "}
            {isAr
              ? "هذا عرض توضيحي بمواعيد ثابتة. للحصول على وكيل صوتي مخصص متصل بنظام الحجوزات الفعلي، تواصل مع فريق المبيعات."
              : "This is a demo with static appointment data. For a custom voice agent connected to your real booking system, contact our sales team."}
          </p>
        </div>
      )}

      {/* Demo Data Info (Development Only) */}
      {process.env.NODE_ENV === "development" && isConnected && (
        <div className="mt-4 p-4 rounded-xl bg-gray-50 dark:bg-gray-900/20 border border-gray-200 dark:border-gray-700/30">
          <details className="cursor-pointer">
            <summary className="text-xs font-medium text-gray-700 dark:text-gray-300">
              {isAr
                ? "📊 بيانات العرض التوضيحي (للمطورين)"
                : "📊 Demo Data (Developers)"}
            </summary>
            <div className="mt-2 text-xs text-gray-600 dark:text-gray-400 space-y-1">
              <p>Agent can reference these demo appointments:</p>
              <ul className="list-disc list-inside space-y-1 mt-2">
                <li>Nov 8, 2025: 09:00, 10:30, 14:00, 15:30</li>
                <li>Nov 9, 2025: 10:00, 11:30, 13:00, 16:00</li>
                <li>Nov 10, 2025: 09:30, 11:00, 14:30, 16:30</li>
              </ul>
            </div>
          </details>
        </div>
      )}
    </div>
  );
}
