import { useState, KeyboardEvent } from 'react'
import { cn } from '@/lib/utils'
import { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger } from '@/components/ui/tooltip'
import { Check, X } from 'lucide-react'

interface ClozeInputProps {
    answer: string
    onSolve: (answer: string) => void
    inputRef?: (el: HTMLInputElement | null) => void
    onTab: () => void
}

export const ClozeInput = ({ answer, onSolve, inputRef, onTab }: ClozeInputProps) => {
    const [value, setValue] = useState('')
    const [status, setStatus] = useState<'idle' | 'correct' | 'incorrect'>('idle')
    const width = Math.max(answer.length, 3) + 2 + 'ch'

    // Check answer on every change
    const handleChange = (e: React.ChangeEvent<HTMLInputElement>) => {
        const val = e.target.value
        setValue(val)

        if (val.toLowerCase() === answer.toLowerCase()) {
            setStatus('correct')
            onSolve(answer)
        } else if (val.length > 0) {
            // Simple logic: if length matches or more it's likely incorrect attempt
            // Or just always incorrect if not matching and not empty? 
            // Let's set incorrect if it's not empty and not correct.
            // But we don't want red while typing "H-e-l-l...".
            // So maybe only if length >= answer.length?
            if (val.length >= answer.length) {
                setStatus('incorrect')
            } else {
                setStatus('idle')
            }
        } else {
            setStatus('idle')
        }
    }

    const handleKeyDown = (e: KeyboardEvent<HTMLInputElement>) => {
        if (e.key === 'Tab') {
            e.preventDefault()
            onTab()
        }
    }

    return (
        <TooltipProvider>
            <Tooltip delayDuration={300}>
                <TooltipTrigger asChild>
                    <div className="relative inline-flex justify-center mx-1 align-baseline translate-y-[4px]">
                        <input
                            ref={inputRef}
                            value={value}
                            onChange={handleChange}
                            onKeyDown={handleKeyDown}
                            disabled={status === 'correct'}
                            className={cn(
                                "text-center outline-none transition-all font-mono font-bold text-lg px-2 py-0.5 rounded",
                                "bg-card shadow-[0_3px_0_hsl(var(--background)),0_3px_8px_rgba(0,0,0,0.1)] border-none",
                                status === 'idle' && "shadow-[0_3px_0_hsl(var(--primary)),0_3px_8px_rgba(0,0,0,0.1)] -translate-y-[2px] focus:translate-y-0 focus:shadow-none",
                                status === 'correct' && "shadow-[0_3px_0_hsl(var(--success)),0_3px_8px_rgba(0,0,0,0.1)] text-green-600 bg-green-50 pr-8",
                                status === 'incorrect' && "shadow-[0_3px_0_hsl(var(--destructive)),0_3px_8px_rgba(0,0,0,0.1)] text-red-500 bg-red-50"
                            )}
                            style={{ width: status === 'correct' ? `calc(${width} + 20px)` : width }}
                            autoComplete="off"
                        />
                        {status === 'correct' && (
                            <div className="absolute right-1 top-1/2 -translate-y-1/2 text-green-600 animate-in zoom-in spin-in-90 duration-300">
                                <Check className="w-4 h-4" />
                            </div>
                        )}
                        {status === 'incorrect' && (
                            <div className="absolute -right-6 top-1/2 -translate-y-1/2 text-red-500 animate-in zoom-in duration-300">
                                <X className="w-4 h-4" />
                            </div>
                        )}
                    </div>
                </TooltipTrigger>
                <TooltipContent>
                    <p>Answer: <strong>{answer}</strong></p>
                </TooltipContent>
            </Tooltip>
        </TooltipProvider>
    )
}
