import React, { useState, useEffect, useRef } from "react";
import { Mic, MicOff, Play, Send, Sparkles, Volume2, HelpCircle, Trash2, Check, RefreshCw, Languages } from "lucide-react";
import { SermonSegment, SermonReference } from "../types";

interface PreacherDashboardProps {
  activeSermon: SermonReference | null;
  segments: SermonSegment[];
  onSegmentsUpdated: (segments: SermonSegment[]) => void;
  onClearSegments: () => void;
}

const SIMULATED_PHRASES = [
  {
    label: "الاستفتاحية والترحيب",
    text: "الحمد لله رب العالمين، والصلاة والسلام على رسول الله الكريم، أشهد أن لا إله إلا الله وأشهد أن محمداً عبده ورسوله.",
  },
  {
    label: "آية تقوى الله (آل عمران)",
    text: "يا أيها الذين آمنوا اتقوا الله حق تقاته ولا تموتن إلا وأنتم مسلمون",
  },
  {
    label: "آية التيسير والفرج (الشرح)",
    text: "إن مع العسر يسرا، إن مع العسر يسرا، فإذا فرغت فانصب وإلى ربك فارغب",
  },
  {
    label: "آية فريضة الصلاة (النساء)",
    text: "أيها الأخوة، صلوا يرحمكم الله، فإن الصلاة كانت على المؤمنين كتابا موقوتا",
  },
  {
    label: "آية إقامة الصلاة (البقرة)",
    text: "وأقيموا الصلاة وآتوا الزكاة واركعوا مع الراكعين، لعلكم تفلحون",
  },
  {
    label: "موعظة عن البر والخير",
    text: "أيها الناس، تصدقوا ولو بشق تمرة، وتعاونوا على البر والتقوى ولا تعاونوا على الإثم والعدوان.",
  },
];

export default function PreacherDashboard({
  activeSermon,
  segments,
  onSegmentsUpdated,
  onClearSegments,
}: PreacherDashboardProps) {
  const [isListening, setIsListening] = useState(false);
  const [customText, setCustomText] = useState("");
  const [isProcessing, setIsProcessing] = useState(false);
  const [errorMsg, setErrorMsg] = useState<string | null>(null);
  const [micStatus, setMicStatus] = useState<"idle" | "listening" | "error" | "unsupported">("idle");
  const [volume, setVolume] = useState(0);

  const recognitionRef = useRef<any>(null);
  const animationFrameRef = useRef<number | null>(null);

  // Initialize browser speech recognition
  useEffect(() => {
    const SpeechRecognition =
      (window as any).SpeechRecognition || (window as any).webkitSpeechRecognition;

    if (!SpeechRecognition) {
      setMicStatus("unsupported");
      return;
    }

    try {
      const rec = new SpeechRecognition();
      rec.continuous = true;
      rec.interimResults = false;
      rec.lang = "ar-SA";

      rec.onstart = () => {
        setIsListening(true);
        setMicStatus("listening");
        startVolumeSimulation();
      };

      rec.onend = () => {
        setIsListening(false);
        setMicStatus(prev => prev === "listening" ? "idle" : prev);
        stopVolumeSimulation();
      };

      rec.onerror = (event: any) => {
        console.error("Speech recognition error", event.error);
        if (event.error === "aborted") {
          setIsListening(false);
          setMicStatus(prev => prev === "listening" ? "idle" : prev);
          stopVolumeSimulation();
          return;
        }
        if (event.error === "not-allowed") {
          setErrorMsg("تم رفض إذن الوصول للميكروفون. يرجى تفعيل الصلاحية من المتصفح.");
          setMicStatus("error");
        } else {
          setErrorMsg(`حدث خطأ في التقاط الصوت: ${event.error}`);
        }
        setIsListening(false);
        stopVolumeSimulation();
      };

      rec.onresult = async (event: any) => {
        const lastResultIndex = event.results.length - 1;
        const result = event.results[lastResultIndex];
        if (result.isFinal) {
          const transcript = result[0].transcript;
          if (transcript && transcript.trim()) {
            await handleProcessSpeech(transcript);
          }
        }
      };

      recognitionRef.current = rec;
    } catch (err: any) {
      console.error("Failed to initialize speech recognition", err);
      setMicStatus("unsupported");
    }

    return () => {
      if (recognitionRef.current) {
        recognitionRef.current.abort();
      }
      stopVolumeSimulation();
    };
  }, []);

  // Volume Simulation for Visual Audio Feedback
  const startVolumeSimulation = () => {
    const step = () => {
      if (Math.random() > 0.3) {
        setVolume(Math.floor(Math.random() * 80) + 10);
      } else {
        setVolume(5);
      }
      animationFrameRef.current = requestAnimationFrame(step);
    };
    animationFrameRef.current = requestAnimationFrame(step);
  };

  const stopVolumeSimulation = () => {
    if (animationFrameRef.current) {
      cancelAnimationFrame(animationFrameRef.current);
    }
    setVolume(0);
  };

  const toggleListening = () => {
    if (!recognitionRef.current) {
      setErrorMsg("ميزة التعرف على الصوت غير مدعومة في هذا المتصفح حالياً.");
      return;
    }

    if (isListening) {
      recognitionRef.current.stop();
    } else {
      setErrorMsg(null);
      try {
        recognitionRef.current.start();
      } catch (err: any) {
        console.error("Start failed", err);
        setErrorMsg("تعذر تشغيل الميكروفون. ربما هو قيد الاستخدام في تبويب آخر.");
      }
    }
  };

  // Process live Arabic speech via full-stack Gemini API
  const handleProcessSpeech = async (textToProcess: string) => {
    if (!textToProcess || !textToProcess.trim()) return;

    setIsProcessing(true);
    setErrorMsg(null);

    try {
      const response = await fetch("/api/translate-and-verify", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ originalText: textToProcess }),
      });

      if (!response.ok) {
        let errMsg = "Failed to process translation";
        try {
          const errorData = await response.json();
          errMsg = errorData.error || errMsg;
        } catch (_) {
          const textError = await response.text();
          errMsg = textError.substring(0, 100) || errMsg;
        }
        throw new Error(errMsg);
      }

      const data = await response.json();
      if (data.success && data.segment) {
        onSegmentsUpdated([...segments, data.segment]);
      }
    } catch (err: any) {
      console.error("Error translation:", err);
      setErrorMsg(err.message || "عذراً، حدث خطأ أثناء الاتصال بالخادم للترجمة.");
    } finally {
      setIsProcessing(false);
    }
  };

  const handleCustomSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    if (!customText.trim() || isProcessing) return;

    const text = customText;
    setCustomText("");
    await handleProcessSpeech(text);
  };

  const handleDeleteSegment = async (id: string) => {
    try {
      const response = await fetch(`/api/segments/${id}`, {
        method: "DELETE",
      });
      if (response.ok) {
        onSegmentsUpdated(segments.filter((seg) => seg.id !== id));
      }
    } catch (err) {
      console.error("Failed to delete segment", err);
    }
  };

  return (
    <div className="space-y-6">
      {/* 1. Voice Capture Dashboard */}
      <div className="bg-white rounded-2xl border border-slate-200 p-6 shadow-sm">
        <div className="flex items-center justify-between mb-6">
          <div className="flex items-center gap-2">
            <span className="relative flex h-3 w-3">
              <span className="animate-ping absolute inline-flex h-full w-full rounded-full bg-red-400 opacity-75"></span>
              <span className="relative inline-flex rounded-full h-3 w-3 bg-red-500"></span>
            </span>
            <h2 className="text-sm font-bold tracking-tight text-slate-800 font-sans uppercase">
              البث الحي والتقاط صوت الخطيب
            </h2>
          </div>
          <div className="text-xs font-semibold px-2.5 py-1 rounded bg-slate-100 text-slate-600 font-sans">
            {micStatus === "listening" && "✓ جاري التقاط الصوت"}
            {micStatus === "idle" && "الميكروفون جاهز"}
            {micStatus === "error" && "⚠️ مشكلة بالاتصال"}
            {micStatus === "unsupported" && "⚠️ المتصفح لا يدعم ميزة الصوت"}
          </div>
        </div>

        <div className="flex flex-col items-center justify-center py-6 border border-slate-100 bg-slate-50/50 rounded-2xl">
          {/* Audio Waves Signal */}
          <div className="h-16 flex items-end gap-1 mb-6">
            {Array.from({ length: 16 }).map((_, i) => {
              const scale = Math.sin((i / 15) * Math.PI);
              const barHeight = isListening ? Math.max(4, volume * scale * (0.5 + Math.random() * 0.5)) : 4;
              return (
                <div
                  key={i}
                  className={`w-1.5 rounded-full transition-all duration-75 ${
                    isListening ? "bg-emerald-500" : "bg-slate-200"
                  }`}
                  style={{ height: `${barHeight}px` }}
                />
              );
            })}
          </div>

          <div className="flex gap-4">
            <button
              type="button"
              onClick={toggleListening}
              className={`w-16 h-16 rounded-full flex items-center justify-center text-white shadow-md transition-all transform hover:scale-105 active:scale-95 ${
                isListening
                  ? "bg-rose-600 hover:bg-rose-700 shadow-rose-100"
                  : "bg-emerald-600 hover:bg-emerald-700 shadow-emerald-100"
              }`}
            >
              {isListening ? <MicOff className="w-6 h-6" /> : <Mic className="w-6 h-6" />}
            </button>
          </div>

          <p className="text-xs font-bold text-slate-700 mt-4 font-sans">
            {isListening ? "انقر لإيقاف الميكروفون" : "انقر لتشغيل الميكروفون والتحدث مباشرة"}
          </p>
          <p className="text-[10px] text-slate-400 mt-1 font-sans">
            يتطلب متصفح كروم أو سفاري، والحديث باللغة العربية الفصحى
          </p>
        </div>

        {errorMsg && (
          <div className="mt-4 bg-rose-50 border border-rose-100 text-rose-700 p-3.5 rounded-xl text-xs font-sans">
            {errorMsg}
          </div>
        )}
      </div>

      {/* 2. Sermon Simulator (Fallback/Demo Helpers) */}
      <div className="bg-slate-50/80 rounded-2xl border border-slate-200 p-6">
        <div className="flex items-center justify-between mb-4">
          <div className="flex items-center gap-2">
            <Sparkles className="w-4 h-4 text-emerald-600 animate-pulse" />
            <h3 className="text-xs font-bold tracking-tight text-slate-800 font-sans uppercase">
              محاكي الخطبة والآيات القرآنية (لتجربة الترجمة والتحقق الفوري)
            </h3>
          </div>
          <span className="text-[10px] bg-slate-100 text-slate-600 px-2 py-0.5 rounded font-semibold font-sans">
            موصى به للتجربة السريعة
          </span>
        </div>
        <p className="text-xs text-slate-500 mb-4 font-sans leading-relaxed">
          انقر فوق أي عبارة من العبارات أدناه لمحاكاة إلقائها من قِبل الخطيب. سيقوم البرنامج فوراً بترجمتها لهندي وإنجليزي عبر الـ AI والتحقق إن كانت آية من القرآن الكريم وجلبها بالرسم المصحفي المشكّل:
        </p>

        <div className="grid grid-cols-1 sm:grid-cols-2 gap-2">
          {SIMULATED_PHRASES.map((phrase, idx) => (
            <button
              key={idx}
              onClick={() => handleProcessSpeech(phrase.text)}
              disabled={isProcessing}
              className="bg-white hover:bg-slate-50/70 border border-slate-200 hover:border-emerald-500/50 text-right p-3 rounded-xl transition-all text-xs font-sans text-slate-700 hover:shadow-sm flex flex-col justify-between h-20 group"
            >
              <span className="font-bold text-slate-800 group-hover:text-emerald-700 transition-colors">
                {phrase.label}
              </span>
              <span className="truncate w-full text-slate-400 text-[10px] mt-1">
                "{phrase.text}"
              </span>
            </button>
          ))}
        </div>
      </div>

      {/* 3. Live Manual Text Feed */}
      <div className="bg-white rounded-2xl border border-slate-200 p-6 shadow-sm">
        <h3 className="text-xs font-bold tracking-tight text-slate-800 mb-3 font-sans uppercase">
          إدخال نص يدوياً خطوة بخطوة
        </h3>
        <form onSubmit={handleCustomSubmit} className="flex gap-2">
          <input
            type="text"
            placeholder="اكتب جملة عربية أو آية قرآنية للتحقق والترجمة فوراً..."
            value={customText}
            onChange={(e) => setCustomText(e.target.value)}
            disabled={isProcessing}
            className="flex-1 text-xs px-4 py-2.5 border border-slate-200 rounded-xl focus:outline-none focus:border-emerald-500 font-sans"
          />
          <button
            type="submit"
            disabled={isProcessing || !customText.trim()}
            className="bg-slate-900 hover:bg-slate-800 text-white rounded-xl px-4 py-2.5 text-xs font-bold flex items-center gap-1.5 transition-colors shrink-0 font-sans"
          >
            {isProcessing ? (
              <RefreshCw className="w-4 h-4 animate-spin" />
            ) : (
              <>
                <Send className="w-3.5 h-3.5" />
                ترجم فوراً
              </>
            )}
          </button>
        </form>
      </div>

      {/* 4. Dashboard Log of Sentences */}
      <div className="bg-white rounded-2xl border border-slate-200 p-6 shadow-sm">
        <div className="flex items-center justify-between mb-4">
          <h3 className="text-xs font-bold tracking-tight text-slate-800 font-sans uppercase">
            سجل الجمل المترجمة والمحفوظة ({segments.length})
          </h3>
          {segments.length > 0 && (
            <button
              onClick={onClearSegments}
              className="text-xs text-rose-600 hover:underline font-semibold font-sans"
            >
              مسح السجل بالكامل
            </button>
          )}
        </div>

        {segments.length === 0 ? (
          <div className="text-center py-8 text-slate-400 text-xs font-sans">
            لا توجد جمل مترجمة حالياً. استخدم الميكروفون أو محاكي الخطبة بالأعلى للبدء.
          </div>
        ) : (
          <div className="divide-y divide-slate-100 max-h-96 overflow-y-auto pr-1">
            {segments
              .slice()
              .reverse()
              .map((seg) => (
                <div key={seg.id} className="py-4 flex gap-3 group">
                  <div className="flex-1 min-w-0">
                    <p className="text-sm font-bold text-slate-800 text-right font-sans">
                      {seg.originalText}
                    </p>
                    <div className="flex flex-col gap-1 mt-2 text-xs">
                      <p className="text-slate-700 font-medium flex items-center gap-1">
                        <span className="text-[9px] font-bold bg-slate-100 px-1.5 py-0.5 rounded text-slate-600">EN</span>
                        {seg.englishTranslation}
                      </p>
                      <p className="text-slate-700 font-medium flex items-center gap-1">
                        <span className="text-[9px] font-bold bg-slate-100 px-1.5 py-0.5 rounded text-slate-600">HI</span>
                        {seg.hindiTranslation}
                      </p>
                    </div>

                    {seg.quranVerse && (
                      <div className="mt-2 bg-emerald-50 border border-emerald-100 rounded-lg p-3 text-right font-sans">
                        <p className="text-[10px] font-bold text-emerald-600 flex items-center justify-between">
                          <span>QURAN VERIFIED • {seg.quranVerse.surahName} [آية {seg.quranVerse.verseNumber}]</span>
                          <span>تم التطابق</span>
                        </p>
                        <p className="text-sm font-serif font-bold text-emerald-950 mt-1 leading-relaxed">
                          {seg.quranVerse.verifiedText}
                        </p>
                      </div>
                    )}
                  </div>
                  <button
                    onClick={() => handleDeleteSegment(seg.id)}
                    className="opacity-0 group-hover:opacity-100 text-rose-500 hover:text-rose-600 p-1.5 hover:bg-rose-50 rounded-lg transition-all shrink-0 self-start"
                    title="حذف الجملة"
                  >
                    <Trash2 className="w-4 h-4" />
                  </button>
                </div>
              ))}
          </div>
        )}
      </div>
    </div>
  );
}
