"use client";

import React, { useState, useRef, useEffect, useCallback } from "react";
import { Play, Pause, Volume2, VolumeX, RotateCcw } from "lucide-react";
import type { Lang } from "@/lib/config";

interface TranscriptLine {
  speaker: "ai" | "customer";
  text: string;
  timestamp: number; // seconds into the audio
}

interface VoiceDemoPlayerProps {
  lang: Lang;
  /** Optional audio source URL. If not provided, uses simulated audio with transcript */
  audioSrc?: string;
  /** Custom transcript lines. Uses default if not provided */
  transcript?: TranscriptLine[];
  /** Title override */
  title?: string;
  /** Subtitle override */
  subtitle?: string;
  /** Auto-play when component comes into view */
  autoPlayOnView?: boolean;
  /** Compact mode for embedding in smaller spaces */
  compact?: boolean;
}

const defaultTranscriptEn: TranscriptLine[] = [
  {
    speaker: "customer",
    text: "Hi, I'd like to book an appointment",
    timestamp: 0,
  },
  {
    speaker: "ai",
    text: "Hello! I'd be happy to help. What service are you looking for?",
    timestamp: 3,
  },
  { speaker: "customer", text: "Dental cleaning", timestamp: 7 },
  {
    speaker: "ai",
    text: "Great! I have openings tomorrow at 10am or 2pm. Which works better?",
    timestamp: 10,
  },
  { speaker: "customer", text: "2pm please", timestamp: 15 },
  {
    speaker: "ai",
    text: "Perfect! I've booked you for a dental cleaning tomorrow at 2pm. You'll receive a confirmation shortly.",
    timestamp: 17,
  },
];

const defaultTranscriptAr: TranscriptLine[] = [
  { speaker: "customer", text: "مرحبًا، أريد حجز موعد", timestamp: 0 },
  {
    speaker: "ai",
    text: "أهلاً! يسعدني مساعدتك. ما الخدمة التي تبحث عنها؟",
    timestamp: 3,
  },
  { speaker: "customer", text: "تنظيف الأسنان", timestamp: 7 },
  {
    speaker: "ai",
    text: "ممتاز! لدي مواعيد متاحة غدًا الساعة 10 صباحًا أو 2 ظهرًا. أيهما أفضل لك؟",
    timestamp: 10,
  },
  { speaker: "customer", text: "الساعة 2 من فضلك", timestamp: 15 },
  {
    speaker: "ai",
    text: "تمام! تم حجز موعدك لتنظيف الأسنان غدًا الساعة 2 ظهرًا. ستتلقى تأكيدًا قريبًا.",
    timestamp: 17,
  },
];

const translations = {
  en: {
    title: "AI Voice Receptionist Demo",
    subtitle: "Listen to a sample conversation with our AI voice agent",
    playDemo: "Play Demo",
    pauseDemo: "Pause",
    replay: "Replay",
    mute: "Mute",
    unmute: "Unmute",
    transcript: "Transcript",
    aiSpeaker: "AI Receptionist",
    customerSpeaker: "Customer",
    liveDemo: "Live Demo",
    duration: "Duration",
    seconds: "s",
  },
  ar: {
    title: "عرض موظف الاستقبال الصوتي بالذكاء الاصطناعي",
    subtitle: "استمع إلى محادثة نموذجية مع وكيلنا الصوتي",
    playDemo: "تشغيل العرض",
    pauseDemo: "إيقاف",
    replay: "إعادة",
    mute: "كتم الصوت",
    unmute: "تشغيل الصوت",
    transcript: "النص",
    aiSpeaker: "موظف الاستقبال AI",
    customerSpeaker: "العميل",
    liveDemo: "عرض مباشر",
    duration: "المدة",
    seconds: "ث",
  },
};

/**
 * VoiceDemoPlayer Component
 *
 * An interactive audio player showcasing the AI voice receptionist capabilities.
 * Features:
 * - Audio playback with animated waveform visualization
 * - Synchronized transcript display
 * - Play/pause/replay controls
 * - Volume control
 * - RTL support for Arabic
 * - Scroll-triggered auto-play option
 * - Keyboard accessible
 *
 * @example
 * <VoiceDemoPlayer lang="en" autoPlayOnView />
 */
export function VoiceDemoPlayer({
  lang,
  audioSrc,
  transcript,
  title,
  subtitle,
  autoPlayOnView = false,
  compact = false,
}: VoiceDemoPlayerProps) {
  const [isPlaying, setIsPlaying] = useState(false);
  const [currentTime, setCurrentTime] = useState(0);
  const [duration, setDuration] = useState(23); // Default duration for simulated audio
  const [isMuted, setIsMuted] = useState(false);
  const [activeLineIndex, setActiveLineIndex] = useState(-1);
  const [hasStarted, setHasStarted] = useState(false);

  const audioRef = useRef<HTMLAudioElement | null>(null);
  const containerRef = useRef<HTMLDivElement>(null);
  const timerRef = useRef<NodeJS.Timeout | null>(null);
  const transcriptRef = useRef<HTMLDivElement>(null);

  const t = translations[lang];
  const isRTL = lang === "ar";
  const transcriptLines =
    transcript || (lang === "ar" ? defaultTranscriptAr : defaultTranscriptEn);

  // Auto-scroll transcript to active line
  useEffect(() => {
    if (activeLineIndex >= 0 && transcriptRef.current) {
      const activeElement = transcriptRef.current.querySelector(
        `[data-line="${activeLineIndex}"]`,
      );
      if (activeElement) {
        activeElement.scrollIntoView({ behavior: "smooth", block: "center" });
      }
    }
  }, [activeLineIndex]);

  // Update active transcript line based on current time
  useEffect(() => {
    let newActiveIndex = -1;
    for (let i = transcriptLines.length - 1; i >= 0; i--) {
      if (currentTime >= transcriptLines[i].timestamp) {
        newActiveIndex = i;
        break;
      }
    }
    setActiveLineIndex(newActiveIndex);
  }, [currentTime, transcriptLines]);

  // Simulated playback (when no audio source)
  const startSimulatedPlayback = useCallback(() => {
    setIsPlaying(true);
    setHasStarted(true);
    timerRef.current = setInterval(() => {
      setCurrentTime((prev) => {
        if (prev >= duration) {
          if (timerRef.current) clearInterval(timerRef.current);
          setIsPlaying(false);
          return duration;
        }
        return prev + 0.1;
      });
    }, 100);
  }, [duration]);

  const stopSimulatedPlayback = useCallback(() => {
    if (timerRef.current) {
      clearInterval(timerRef.current);
      timerRef.current = null;
    }
    setIsPlaying(false);
  }, []);

  // Handle play/pause
  const handlePlayPause = useCallback(() => {
    if (audioSrc && audioRef.current) {
      if (isPlaying) {
        audioRef.current.pause();
      } else {
        audioRef.current.play();
      }
      setIsPlaying(!isPlaying);
      setHasStarted(true);
    } else {
      if (isPlaying) {
        stopSimulatedPlayback();
      } else {
        startSimulatedPlayback();
      }
    }
  }, [audioSrc, isPlaying, startSimulatedPlayback, stopSimulatedPlayback]);

  // Handle replay
  const handleReplay = useCallback(() => {
    setCurrentTime(0);
    setActiveLineIndex(-1);
    if (audioSrc && audioRef.current) {
      audioRef.current.currentTime = 0;
      audioRef.current.play();
      setIsPlaying(true);
    } else {
      stopSimulatedPlayback();
      startSimulatedPlayback();
    }
  }, [audioSrc, startSimulatedPlayback, stopSimulatedPlayback]);

  // Handle mute toggle
  const handleMuteToggle = useCallback(() => {
    if (audioRef.current) {
      audioRef.current.muted = !isMuted;
    }
    setIsMuted(!isMuted);
  }, [isMuted]);

  // Intersection Observer for auto-play
  useEffect(() => {
    if (!autoPlayOnView || hasStarted) return;

    const observer = new IntersectionObserver(
      (entries) => {
        entries.forEach((entry) => {
          if (entry.isIntersecting && !hasStarted) {
            handlePlayPause();
          }
        });
      },
      { threshold: 0.5 },
    );

    if (containerRef.current) {
      observer.observe(containerRef.current);
    }

    return () => observer.disconnect();
  }, [autoPlayOnView, hasStarted, handlePlayPause]);

  // Cleanup on unmount
  useEffect(() => {
    return () => {
      if (timerRef.current) clearInterval(timerRef.current);
    };
  }, []);

  // Progress percentage
  const progress = (currentTime / duration) * 100;

  // Format time display
  const formatTime = (time: number) => {
    const mins = Math.floor(time / 60);
    const secs = Math.floor(time % 60);
    return `${mins}:${secs.toString().padStart(2, "0")}`;
  };

  return (
    <div
      ref={containerRef}
      className={`w-full ${compact ? "max-w-md" : "max-w-2xl"} mx-auto`}
      dir={isRTL ? "rtl" : "ltr"}
    >
      {/* Hidden audio element */}
      {audioSrc && (
        <audio
          ref={audioRef}
          src={audioSrc}
          onTimeUpdate={(e) => setCurrentTime(e.currentTarget.currentTime)}
          onDurationChange={(e) => setDuration(e.currentTarget.duration)}
          onEnded={() => setIsPlaying(false)}
          preload="metadata"
        />
      )}

      <div className="bg-gradient-to-br from-white to-purple-50/30 dark:from-slate-900 dark:to-purple-900/10 rounded-2xl border-2 border-purple-200 dark:border-purple-700/50 shadow-xl overflow-hidden">
        {/* Header */}
        {!compact && (
          <div className="px-6 pt-6 pb-4">
            <div className="flex items-center gap-2 mb-2">
              <span className="inline-flex items-center gap-1.5 px-2.5 py-1 rounded-full bg-purple-100 dark:bg-purple-900/30 text-purple-700 dark:text-purple-400 text-xs font-medium">
                <span className="w-2 h-2 rounded-full bg-purple-500 animate-pulse" />
                {t.liveDemo}
              </span>
            </div>
            <h3 className="text-xl font-bold text-slate-900 dark:text-white">
              {title || t.title}
            </h3>
            <p className="text-sm text-slate-600 dark:text-slate-400 mt-1">
              {subtitle || t.subtitle}
            </p>
          </div>
        )}

        {/* Waveform Visualization */}
        <div className="relative px-6 py-4 bg-slate-100/50 dark:bg-slate-800/50">
          <div
            className="flex items-center justify-center gap-0.5 h-16"
            aria-hidden="true"
          >
            {Array.from({ length: 40 }).map((_, i) => {
              const baseHeight = Math.sin((i / 40) * Math.PI * 3) * 0.5 + 0.5;
              const isActive = isPlaying && (progress / 100) * 40 > i;
              const animationHeight = isPlaying
                ? Math.random() * 0.4 + 0.3
                : 0.2;

              return (
                <div
                  key={i}
                  className={`w-1 rounded-full transition-all duration-150 ${
                    isActive
                      ? "bg-purple-500 dark:bg-purple-400"
                      : (progress / 100) * 40 > i
                        ? "bg-purple-400 dark:bg-purple-500"
                        : "bg-slate-300 dark:bg-slate-600"
                  }`}
                  style={{
                    height: `${(isActive ? animationHeight : baseHeight * 0.3 + 0.1) * 100}%`,
                    opacity: isActive ? 1 : 0.7,
                  }}
                />
              );
            })}
          </div>

          {/* Progress bar */}
          <div className="mt-3 relative h-1 bg-slate-200 dark:bg-slate-700 rounded-full overflow-hidden">
            <div
              className="absolute top-0 left-0 h-full bg-gradient-to-r from-purple-500 to-indigo-500 rounded-full transition-all duration-100"
              style={{ width: `${progress}%` }}
            />
          </div>

          {/* Time display */}
          <div className="flex justify-between mt-2 text-xs text-slate-500 dark:text-slate-400">
            <span>{formatTime(currentTime)}</span>
            <span>{formatTime(duration)}</span>
          </div>
        </div>

        {/* Controls */}
        <div className="px-6 py-4 flex items-center justify-center gap-4">
          {/* Replay button */}
          <button
            onClick={handleReplay}
            disabled={!hasStarted}
            className="p-2 rounded-full text-slate-500 hover:text-purple-600 hover:bg-purple-100 dark:hover:bg-purple-900/30 transition-colors disabled:opacity-50 disabled:cursor-not-allowed"
            aria-label={t.replay}
            title={t.replay}
          >
            <RotateCcw className="w-5 h-5" />
          </button>

          {/* Play/Pause button */}
          <button
            onClick={handlePlayPause}
            className="w-14 h-14 rounded-full bg-gradient-to-br from-purple-500 to-indigo-600 text-white flex items-center justify-center shadow-lg hover:shadow-xl hover:scale-105 transition-all focus:outline-none focus:ring-2 focus:ring-purple-500 focus:ring-offset-2 dark:focus:ring-offset-slate-900"
            aria-label={isPlaying ? t.pauseDemo : t.playDemo}
          >
            {isPlaying ? (
              <Pause className="w-6 h-6" />
            ) : (
              <Play className="w-6 h-6 ml-0.5" />
            )}
          </button>

          {/* Mute button */}
          <button
            onClick={handleMuteToggle}
            className="p-2 rounded-full text-slate-500 hover:text-purple-600 hover:bg-purple-100 dark:hover:bg-purple-900/30 transition-colors"
            aria-label={isMuted ? t.unmute : t.mute}
            title={isMuted ? t.unmute : t.mute}
          >
            {isMuted ? (
              <VolumeX className="w-5 h-5" />
            ) : (
              <Volume2 className="w-5 h-5" />
            )}
          </button>
        </div>

        {/* Transcript */}
        {!compact && (
          <div className="px-6 pb-6">
            <h4 className="text-sm font-semibold text-slate-700 dark:text-slate-300 mb-3 flex items-center gap-2">
              <span className="text-purple-500">📝</span>
              {t.transcript}
            </h4>
            <div
              ref={transcriptRef}
              className="max-h-64 overflow-y-auto space-y-2 scrollbar-thin scrollbar-thumb-purple-200 dark:scrollbar-thumb-purple-800 scrollbar-track-transparent"
            >
              {transcriptLines.map((line, index) => (
                <div
                  key={index}
                  data-line={index}
                  className={`p-3 rounded-lg transition-all duration-300 ${
                    index === activeLineIndex
                      ? "bg-purple-100 dark:bg-purple-900/30 border-l-4 border-purple-500"
                      : index < activeLineIndex
                        ? "bg-slate-50 dark:bg-slate-800/50 opacity-70"
                        : "bg-slate-50 dark:bg-slate-800/50 opacity-50"
                  }`}
                >
                  <div
                    className={`flex items-start gap-3 ${isRTL ? "flex-row-reverse" : ""}`}
                  >
                    <div
                      className={`flex-shrink-0 w-8 h-8 rounded-full flex items-center justify-center text-sm ${
                        line.speaker === "ai"
                          ? "bg-purple-200 dark:bg-purple-800 text-purple-700 dark:text-purple-300"
                          : "bg-emerald-200 dark:bg-emerald-800 text-emerald-700 dark:text-emerald-300"
                      }`}
                    >
                      {line.speaker === "ai" ? "🤖" : "👤"}
                    </div>
                    <div className={`flex-1 ${isRTL ? "text-right" : ""}`}>
                      <span className="text-xs font-medium text-slate-500 dark:text-slate-400 block mb-0.5">
                        {line.speaker === "ai"
                          ? t.aiSpeaker
                          : t.customerSpeaker}
                      </span>
                      <p className="text-sm text-slate-700 dark:text-slate-300">
                        {line.text}
                      </p>
                    </div>
                  </div>
                </div>
              ))}
            </div>
          </div>
        )}
      </div>
    </div>
  );
}

export default VoiceDemoPlayer;
