import { useState, useRef, useEffect } from "react";
import arTaskPromptAudio from "../assets/audio/ar_task_prompt.mp3";
import enTaskPromptAudio from "../assets/audio/en_task_prompt.mp3";

const NUM_BARS = 18;
const SR = window.SpeechRecognition || window.webkitSpeechRecognition;

export default function VoiceTaskUpdateWidget({
  onUpdateConfirmed,
  isSubmitting = false,
}) {
  // phase: prompted | ready | listening | preview | saved
  const [phase, setPhase]           = useState("prompted");
  const [transcript, setTranscript] = useState("");
  const [editableText, setEditableText] = useState("");
  const [barHeights, setBarHeights] = useState(Array(NUM_BARS).fill(4));
  // "en" | "ar"
  const [lang, setLang]             = useState("en");

  const audioCtxRef    = useRef(null);
  const sourceRef      = useRef(null);
  const animFrameRef   = useRef(null);
  const recognitionRef = useRef(null);
  const streamRef      = useRef(null);
  const autoStopRef    = useRef(null);
  const transcriptRef  = useRef(""); // tracks live transcript for onend access

  const isArabic = lang === "ar";

  // ── Mount ─────────────────────────────────────────────────────────────────
  useEffect(() => {
    const timer = setTimeout(() => playPromptForLang(lang), 800);
    return () => { clearTimeout(timer); cleanup(); };
  }, []);

  // ── Replay when language tab changes ─────────────────────────────────────
  const isFirstLangRender = useRef(true);
  useEffect(() => {
    if (isFirstLangRender.current) { isFirstLangRender.current = false; return; }
    if (phase === "listening" || phase === "preview" || phase === "saved") return;
    if (window.speechSynthesis) window.speechSynthesis.cancel();
    setPhase("prompted");
    const capturedLang = lang;
    const timer = setTimeout(() => playPromptForLang(capturedLang), 400);
    return () => clearTimeout(timer);
  }, [lang]);

  function playPromptForLang(currentLang) {
    // Use pre-recorded MP3 for both languages — fixes Android speechSynthesis issues
    const audioFile = currentLang === "ar" ? arTaskPromptAudio : enTaskPromptAudio;
    const audio = new Audio(audioFile);
    audio.onended = () => setPhase("ready");
    audio.onerror = () => setPhase("ready");
    audio.play().catch(() => setPhase("ready"));
  }

  function cleanup() {
    if (autoStopRef.current)  clearTimeout(autoStopRef.current);
    if (animFrameRef.current) cancelAnimationFrame(animFrameRef.current);
    if (sourceRef.current)    { sourceRef.current.disconnect(); sourceRef.current = null; }
    if (audioCtxRef.current)  { audioCtxRef.current.close();    audioCtxRef.current = null; }
    if (streamRef.current)    { streamRef.current.getTracks().forEach((t) => t.stop()); streamRef.current = null; }
    if (recognitionRef.current) {
      try { recognitionRef.current.stop(); } catch (_) {}
      recognitionRef.current = null;
    }
    setBarHeights(Array(NUM_BARS).fill(4));
  }

  async function startWaveform() {
    try {
      const stream = await navigator.mediaDevices.getUserMedia({ audio: true });
      streamRef.current = stream;
      const ctx = new (window.AudioContext || window.webkitAudioContext)();
      audioCtxRef.current = ctx;
      const analyser = ctx.createAnalyser();
      analyser.fftSize = 64;
      const src = ctx.createMediaStreamSource(stream);
      sourceRef.current = src;
      src.connect(analyser);
      const data = new Uint8Array(analyser.frequencyBinCount);
      function frame() {
        animFrameRef.current = requestAnimationFrame(frame);
        analyser.getByteFrequencyData(data);
        setBarHeights(
          Array.from({ length: NUM_BARS }, (_, i) => {
            const idx = Math.floor((i * data.length) / NUM_BARS);
            return 4 + (data[idx] / 255) * 22;
          })
        );
      }
      frame();
    } catch (_) {}
  }

  async function handleSpeak() {
    setPhase("listening");
    setTranscript("");
    setEditableText("");
    transcriptRef.current = "";
    await startWaveform();

    if (!SR) { cleanup(); setPhase("ready"); return; }

    const rec = new SR();
    recognitionRef.current = rec;
    rec.lang = isArabic ? "ar-SA" : "en-US";
    rec.interimResults = false; // No interim — only get final results, prevents duplicates
    rec.continuous = false;     // Single utterance mode
    rec.maxAlternatives = 1;

    rec.onresult = (e) => {
      // Take only the last result's transcript — Android may send multiple onresult events
      // but each contains the best single transcript so far. The last one is most accurate.
      const lastResult = e.results[e.resultIndex];
      if (lastResult && lastResult.isFinal) {
        const text = lastResult[0].transcript.trim();
        transcriptRef.current = text;
        setTranscript(text);
      }
    };

    rec.onend = () => {
      cleanup();
      const result = transcriptRef.current.trim();
      if (result.length > 0) {
        setEditableText(result);
        setPhase("preview");
      } else {
        setPhase("ready");
      }
    };

    rec.onerror = () => { cleanup(); setPhase("ready"); };
    rec.start();

    // Auto-stop after 15s as safety fallback
    autoStopRef.current = setTimeout(() => {
      if (recognitionRef.current) recognitionRef.current.stop();
    }, 15000);
  }

  function handleStopListening() {
    if (recognitionRef.current) recognitionRef.current.stop();
  }

  function handleConfirm() {
    if (!editableText.trim() || isSubmitting) return;
    onUpdateConfirmed(editableText.trim());
    setPhase("saved");
  }

  function handleRetry() {
    cleanup();
    setTranscript("");
    setEditableText("");
    transcriptRef.current = "";
    setPhase("ready");
  }

  function handleReset() {
    cleanup();
    setTranscript("");
    setEditableText("");
    transcriptRef.current = "";
    setPhase("prompted");
    if (window.speechSynthesis) window.speechSynthesis.cancel();
    setTimeout(() => playPromptForLang(lang), 400);
  }

  return (
    <div style={styles.card}>
      {/* Header */}
      <div style={styles.header}>
        <div style={styles.logo}>📝</div>
        <div style={styles.brand}>SEERA<span style={styles.brandAccent}>-ASM</span></div>
        <span style={styles.badge}>Task Update</span>
      </div>

      <div style={styles.title}>Voice Task Update</div>
      <div style={styles.subtitle}>
        Speak your progress note — it will be added to Task Updates
      </div>

      {/* ── 2-tab language toggle ── */}
      <div style={{
        display: "flex", gap: 6, marginBottom: 16,
        background: "#f1f5f9", borderRadius: 10, padding: 4,
      }}>
        {[{ key: "en", label: "English" }, { key: "ar", label: "عربي" }].map(({ key, label }) => (
          <button
            key={key}
            onClick={() => setLang(key)}
            style={{
              flex: 1, padding: "6px 0", borderRadius: 7, border: "none",
              fontSize: 12, fontWeight: 600, cursor: "pointer", transition: "all 0.15s",
              background: lang === key ? "#fff" : "transparent",
              color: lang === key ? "#7c3aed" : "#64748b",
              boxShadow: lang === key ? "0 1px 4px rgba(0,0,0,0.1)" : "none",
            }}
          >
            {label}
          </button>
        ))}
      </div>

      {/* Action area */}
      <div style={styles.actionArea}>

        {phase === "prompted" && (
          <div style={{ ...styles.statusMsg, ...styles.speakingMsg }}>
            <div style={styles.speakingIcon}>🔊</div>
            <div style={styles.speakingText}>
              {isArabic ? "يرجى الانتظار…" : "Please wait…"}
            </div>
            <div style={styles.dots}>
              <span style={styles.dot} />
              <span style={{ ...styles.dot, animationDelay: "0.2s" }} />
              <span style={{ ...styles.dot, animationDelay: "0.4s" }} />
            </div>
          </div>
        )}

        {phase === "ready" && (
          <button style={styles.speakBtn} onClick={handleSpeak}>
            <div style={styles.speakBtnIcon}>🎙️</div>
            <div>
              <span style={styles.speakBtnTitle}>
                {isArabic ? "اضغط للتحدث" : "Tap to Speak"}
              </span>
              <span style={styles.speakBtnHint}>
                {isArabic ? "تحدث عن تحديث مهمتك بوضوح" : "Speak your task update clearly"}
              </span>
            </div>
          </button>
        )}

        {phase === "listening" && (
          <div style={styles.listeningArea}>
            <div style={styles.micActive}>🔴</div>
            <div style={styles.waveform}>
              {barHeights.map((h, i) => (
                <div key={i} style={{ ...styles.bar, height: `${h}px` }} />
              ))}
            </div>
            <div style={styles.micLabel}>
              {isArabic ? "جاري الاستماع… تحدث الآن" : "Listening… speak your update"}
            </div>
            {transcript && (
              <div style={styles.liveTranscript}>
                <em style={{ color: "#64748b", fontSize: 12 }}>
                  {isArabic ? "يسمع:" : "Hearing:"}
                </em>
                <p style={{
                  margin: "4px 0 0", fontSize: 13, color: "#1e293b",
                  direction: isArabic ? "rtl" : "ltr",
                }}>
                  {transcript}
                </p>
              </div>
            )}
            <button style={styles.stopBtn} onClick={handleStopListening}>
              {isArabic ? "⏹ انتهيت" : "⏹ Done Speaking"}
            </button>
          </div>
        )}

        {phase === "preview" && (
          <div style={styles.previewArea}>
            <div style={styles.previewLabel}>
              {isArabic ? "✅ تم! راجع وعدّل إذا لزم:" : "✅ Got it! Review and edit if needed:"}
            </div>
            <textarea
              style={{ ...styles.textarea, direction: isArabic ? "rtl" : "ltr" }}
              value={editableText}
              onChange={e => setEditableText(e.target.value)}
              rows={4}
              placeholder={isArabic ? "نص التحديث…" : "Your update text…"}
              autoFocus
            />
            <p style={styles.previewHint}>
              {isArabic ? "📅 سيتم إضافة تاريخ اليوم تلقائياً" : "📅 Today's date will be added automatically"}
            </p>
          </div>
        )}

        {phase === "saved" && (
          <div style={{ ...styles.statusMsg, ...styles.savedMsg }}>
            {isArabic ? "✅ تمت إضافة التحديث!" : "✅ Update added to task!"}
          </div>
        )}
      </div>

      {/* Bottom actions */}
      <div style={styles.actions}>
        {phase !== "saved" && (
          <button style={styles.ghostBtn} onClick={handleReset} disabled={isSubmitting}>
            {isArabic ? "إعادة" : "Reset"}
          </button>
        )}
        {phase === "listening" && (
          <button style={{ ...styles.primaryBtn, background: "#dc2626" }} onClick={handleStopListening}>
            {isArabic ? "إيقاف" : "Stop"}
          </button>
        )}
        {phase === "preview" && (
          <>
            <button style={styles.ghostBtn} onClick={handleRetry}>
              {isArabic ? "🔄 إعادة التسجيل" : "🔄 Re-record"}
            </button>
            <button
              style={{ ...styles.primaryBtn, ...(isSubmitting ? styles.disabledBtn : {}) }}
              onClick={handleConfirm}
              disabled={isSubmitting || !editableText.trim()}
            >
              {isSubmitting
                ? (isArabic ? "جاري الحفظ…" : "Saving…")
                : (isArabic ? "✅ إضافة التحديث" : "✅ Add Update")}
            </button>
          </>
        )}
        {phase === "saved" && (
          <button style={styles.ghostBtn} onClick={handleReset}>
            {isArabic ? "إضافة تحديث آخر" : "Add Another"}
          </button>
        )}
      </div>
    </div>
  );
}

const styles = {
  card: {
    background: "#ffffff", border: "1px solid #e2e8f0", borderRadius: 16,
    padding: "28px 28px 24px", width: "100%", maxWidth: 480,
    boxShadow: "0 8px 32px rgba(0,0,0,0.12)", fontFamily: "inherit", color: "#1e293b",
  },
  header: { display: "flex", alignItems: "center", gap: 10, marginBottom: 20 },
  logo: {
    width: 36, height: 36, borderRadius: 8,
    background: "linear-gradient(135deg,#8b5cf6,#7c3aed)",
    display: "flex", alignItems: "center", justifyContent: "center", fontSize: 16,
  },
  brand: { fontWeight: 700, fontSize: 15, letterSpacing: "0.03em", color: "#1e293b" },
  brandAccent: { color: "#7c3aed" },
  badge: {
    marginLeft: "auto", background: "#f5f3ff", border: "1px solid #ddd6fe",
    color: "#6d28d9", fontSize: 11, fontWeight: 600, padding: "3px 10px", borderRadius: 100,
  },
  title:    { fontSize: 22, fontWeight: 700, marginBottom: 4 },
  subtitle: { fontSize: 13, color: "#64748b", marginBottom: 12 },
  actionArea: {
    display: "flex", flexDirection: "column", alignItems: "center",
    gap: 12, marginBottom: 20, minHeight: 100, justifyContent: "center",
  },
  statusMsg: {
    display: "flex", alignItems: "center", gap: 10, fontSize: 14,
    fontWeight: 600, padding: "16px 20px", borderRadius: 10, width: "100%",
  },
  speakingMsg: {
    flexDirection: "column", background: "#f5f3ff",
    border: "1px solid #ddd6fe", color: "#7c3aed", gap: 8,
  },
  savedMsg: {
    background: "#f0fdf4", border: "1px solid #bbf7d0",
    color: "#16a34a", fontSize: 16, justifyContent: "center",
  },
  speakingIcon: { fontSize: 28 },
  speakingText: { fontSize: 14, fontWeight: 600, color: "#7c3aed" },
  dots: { display: "flex", gap: 4 },
  dot: {
    display: "inline-block", width: 6, height: 6, borderRadius: "50%",
    background: "#8b5cf6", animation: "vsw-dot 1.2s ease-in-out infinite",
  },
  speakBtn: {
    width: "100%", padding: "14px 16px", borderRadius: 12,
    border: "1px solid #ddd6fe", background: "#f5f3ff", color: "#5b21b6",
    fontFamily: "inherit", cursor: "pointer", display: "flex",
    alignItems: "center", gap: 12, transition: "all 0.2s",
  },
  speakBtnIcon: {
    width: 40, height: 40, borderRadius: "50%", background: "#7c3aed",
    color: "#fff", display: "flex", alignItems: "center", justifyContent: "center",
    fontSize: 18, flexShrink: 0,
  },
  speakBtnTitle: { display: "block", fontSize: 15, fontWeight: 600, color: "#5b21b6" },
  speakBtnHint:  { display: "block", fontSize: 11, color: "#8b5cf6", marginTop: 2 },
  listeningArea: { display: "flex", flexDirection: "column", alignItems: "center", gap: 8, width: "100%" },
  micActive: { fontSize: 36 },
  waveform:  { display: "flex", alignItems: "center", gap: 3, height: 30 },
  bar: { width: 3, borderRadius: 2, background: "linear-gradient(to top,#8b5cf6,#c4b5fd)", transition: "height 0.08s ease" },
  micLabel: { fontSize: 13, color: "#ef4444", fontWeight: 600 },
  liveTranscript: {
    width: "100%", background: "#f8fafc", border: "1px solid #e2e8f0",
    borderRadius: 8, padding: "8px 12px", marginTop: 4,
  },
  stopBtn: {
    marginTop: 8, padding: "8px 20px", borderRadius: 8,
    border: "1px solid #fecaca", background: "#fef2f2",
    color: "#dc2626", fontFamily: "inherit", fontSize: 13, fontWeight: 600, cursor: "pointer",
  },
  previewArea:  { width: "100%" },
  previewLabel: { fontSize: 13, fontWeight: 600, color: "#16a34a", marginBottom: 8 },
  textarea: {
    width: "100%", padding: "10px 12px", border: "1px solid #c4b5fd",
    borderRadius: 8, fontSize: 14, fontFamily: "inherit", color: "#1e293b",
    background: "#fafafa", resize: "vertical", outline: "none", boxSizing: "border-box",
  },
  previewHint: { fontSize: 11, color: "#64748b", marginTop: 6 },
  actions:    { display: "flex", gap: 10 },
  ghostBtn:   {
    flex: 1, padding: "10px 18px", borderRadius: 8,
    border: "1px solid #e2e8f0", background: "#f1f5f9",
    color: "#475569", fontFamily: "inherit", fontSize: 14, fontWeight: 600, cursor: "pointer",
  },
  primaryBtn: {
    flex: 1, padding: "10px 18px", borderRadius: 8, border: "none",
    background: "#7c3aed", color: "#fff", fontFamily: "inherit",
    fontSize: 14, fontWeight: 600, cursor: "pointer",
  },
  disabledBtn: { opacity: 0.45, cursor: "not-allowed" },
};