import React, { useState, useEffect } from 'react';
import { cn } from '@/lib/utils';
import { CheckCircle2, Volume2 } from 'lucide-react';

interface SpellingBeeQuestionProps {
    options: Array<{ answer?: string }>;
    onSubmit: (answerData: { answer: string }) => void;
    disabled?: boolean;
}

export default function SpellingBeeQuestion({ options, onSubmit, disabled }: SpellingBeeQuestionProps) {
    const [inputValue, setInputValue] = useState('');
    const [isPlaying, setIsPlaying] = useState(false);
    
    // We get the word to play from the question data, but it's hidden during live play.
    // However, we need it to use TTS. Since the backend unsets `answer`, we cannot use SpeechSynthesis directly on the client if it's hidden.
    // Wait, if the backend unsets it, how can the frontend play it?
    // Good point! The backend MUST NOT unset the `answer` for spelling_bee if we rely on client-side TTS, 
    // OR the backend must generate an audio file URL.
    // Wait, our implementation plan said: "Menggunakan Web Speech API (speechSynthesis) untuk membacakan teks".
    // If we use Web Speech API, the frontend needs the text.
    // If we hide the text, the frontend can't read it.
    // Ah, this means for Spelling Bee, we need a separate field or we MUST NOT hide the answer from the client (which exposes it to devtools).
    // Let's assume we don't hide it for Spelling Bee, or we hide it and use a backend TTS route.
    // For now, let's assume we have it in options[0].answer. 
    // Let's pass it. Wait, I'll update the backend to NOT unset the answer for spelling_bee!
    
    const wordToSpeak = options?.[0]?.answer || '';

    const playAudio = () => {
        if (!wordToSpeak || isPlaying) return;
        
        setIsPlaying(true);
        const utterance = new SpeechSynthesisUtterance(wordToSpeak);
        utterance.lang = 'en-US';
        utterance.rate = 0.8; // slightly slower for spelling bee
        
        utterance.onend = () => setIsPlaying(false);
        utterance.onerror = () => setIsPlaying(false);
        
        window.speechSynthesis.speak(utterance);
    };

    // Auto play once when component mounts
    useEffect(() => {
        if (wordToSpeak && !disabled) {
            const timer = setTimeout(() => {
                playAudio();
            }, 500);
            return () => clearTimeout(timer);
        }
    }, [wordToSpeak, disabled]);

    const handleSubmit = (e?: React.FormEvent) => {
        e?.preventDefault();
        if (disabled || !inputValue.trim()) return;
        onSubmit({ answer: inputValue.trim() });
    };

    return (
        <div className="flex flex-col gap-8 max-w-2xl mx-auto w-full items-center">
            <div className="text-center text-slate-300">
                Dengarkan kata yang diucapkan dan ketik ejaannya dengan benar.
            </div>

            <button
                onClick={playAudio}
                disabled={isPlaying}
                className={cn(
                    "w-24 h-24 rounded-full flex items-center justify-center transition-all shadow-xl",
                    isPlaying 
                        ? "bg-primary-500/50 text-primary-200 animate-pulse cursor-wait scale-95" 
                        : "bg-primary-600 text-white hover:bg-primary-500 hover:scale-105 active:scale-95 cursor-pointer"
                )}
            >
                <Volume2 className={cn("w-12 h-12", isPlaying ? "animate-bounce" : "")} />
            </button>
            
            <div className="text-sm font-medium text-slate-400 -mt-4">
                {isPlaying ? "Sedang memutar..." : "Ketuk untuk mendengarkan"}
            </div>

            <form onSubmit={handleSubmit} className="w-full max-w-md flex flex-col gap-6 items-center">
                <input
                    type="text"
                    value={inputValue}
                    onChange={(e) => setInputValue(e.target.value)}
                    disabled={disabled}
                    placeholder="Ketik kata di sini..."
                    className="w-full text-center text-2xl md:text-3xl font-bold py-4 px-6 rounded-2xl bg-slate-800/50 border-2 border-slate-700/50 text-white placeholder-slate-500 focus:border-primary-500 focus:ring-1 focus:ring-primary-500 uppercase tracking-widest disabled:opacity-50"
                    autoFocus
                    autoComplete="off"
                    spellCheck="false"
                />
                
                {!disabled && (
                    <button
                        type="submit"
                        disabled={!inputValue.trim()}
                        className={cn(
                            "flex items-center gap-2 px-8 py-4 rounded-full font-bold text-lg transition-all shadow-lg",
                            inputValue.trim()
                                ? "bg-emerald-500 hover:bg-emerald-400 text-white shadow-emerald-500/30 hover:-translate-y-1"
                                : "bg-slate-700 text-slate-400 cursor-not-allowed opacity-50"
                        )}
                    >
                        <CheckCircle2 className="w-6 h-6" />
                        Kirim Jawaban
                    </button>
                )}
            </form>
        </div>
    );
}
