'use client'

import React, { useState, useRef, useEffect } from 'react'

interface TypeInputProps {
  prompt: string
  answer: string
  onResult: (correct: boolean) => void
  isDark: boolean
}

function levenshtein(a: string, b: string): number {
  const m = a.length
  const n = b.length
  const dp: number[][] = Array.from({ length: m + 1 }, () => Array(n + 1).fill(0))
  for (let i = 0; i <= m; i++) dp[i][0] = i
  for (let j = 0; j <= n; j++) dp[0][j] = j
  for (let i = 1; i <= m; i++) {
    for (let j = 1; j <= n; j++) {
      dp[i][j] = Math.min(
        dp[i - 1][j] + 1,
        dp[i][j - 1] + 1,
        dp[i - 1][j - 1] + (a[i - 1] === b[j - 1] ? 0 : 1)
      )
    }
  }
  return dp[m][n]
}

export function TypeInput({ prompt, answer, onResult, isDark }: TypeInputProps) {
  const [input, setInput] = useState('')
  const [feedback, setFeedback] = useState<'correct' | 'almost' | 'wrong' | null>(null)
  const inputRef = useRef<HTMLInputElement>(null)

  useEffect(() => {
    setInput('')
    setFeedback(null)
    inputRef.current?.focus()
  }, [prompt, answer])

  const handleSubmit = (e: React.FormEvent) => {
    e.preventDefault()
    const userAnswer = input.trim().toLowerCase()
    const correctAnswer = answer.trim().toLowerCase()

    if (userAnswer === correctAnswer) {
      setFeedback('correct')
      setTimeout(() => onResult(true), 800)
    } else if (levenshtein(userAnswer, correctAnswer) <= 2) {
      setFeedback('almost')
      setTimeout(() => {
        setFeedback('wrong')
        setTimeout(() => onResult(false), 2000)
      }, 1500)
    } else {
      setFeedback('wrong')
      setTimeout(() => onResult(false), 2500)
    }
  }

  const feedbackColors = {
    correct: isDark ? 'border-green-400 bg-green-500/20' : 'border-green-500 bg-green-50',
    almost: isDark ? 'border-yellow-400 bg-yellow-500/20' : 'border-yellow-500 bg-yellow-50',
    wrong: isDark ? 'border-red-400 bg-red-500/20' : 'border-red-500 bg-red-50',
  }

  return (
    <div className="w-full max-w-lg mx-auto space-y-6">
      {/* Prompt */}
      <div className={`text-center p-8 rounded-3xl ${isDark ? 'bg-white/10 backdrop-blur-xl border border-white/20' : 'bg-white shadow-xl border border-slate-200'}`}>
        <span className={`text-xs font-medium ${isDark ? 'text-white/40' : 'text-slate-400'}`}>
          UEBERSETZE
        </span>
        <p className={`text-3xl font-bold mt-2 ${isDark ? 'text-white' : 'text-slate-900'}`}>
          {prompt}
        </p>
      </div>

      {/* Input */}
      <form onSubmit={handleSubmit}>
        <div className={`rounded-2xl overflow-hidden border-2 transition-colors ${
          feedback ? feedbackColors[feedback] : (isDark ? 'border-white/20' : 'border-slate-200')
        }`}>
          <input
            ref={inputRef}
            type="text"
            value={input}
            onChange={(e) => setInput(e.target.value)}
            disabled={feedback !== null}
            placeholder="Antwort eintippen..."
            autoComplete="off"
            autoCorrect="off"
            spellCheck={false}
            className={`w-full px-6 py-4 text-xl text-center outline-none ${
              isDark
                ? 'bg-transparent text-white placeholder-white/30'
                : 'bg-transparent text-slate-900 placeholder-slate-400'
            }`}
          />
        </div>

        {!feedback && (
          <button
            type="submit"
            disabled={!input.trim()}
            className={`w-full mt-4 py-3 rounded-xl font-medium transition-all ${
              input.trim()
                ? 'bg-gradient-to-r from-blue-500 to-cyan-500 text-white hover:shadow-lg'
                : isDark ? 'bg-white/5 text-white/30' : 'bg-slate-100 text-slate-400'
            }`}
          >
            Pruefen
          </button>
        )}
      </form>

      {/* Feedback Message */}
      {feedback === 'correct' && (
        <div className="text-center">
          <span className="text-2xl">✅</span>
          <p className={`text-lg font-semibold mt-1 ${isDark ? 'text-green-300' : 'text-green-600'}`}>
            Richtig!
          </p>
        </div>
      )}

      {feedback === 'almost' && (
        <div className="text-center">
          <span className="text-2xl">🤏</span>
          <p className={`text-lg font-semibold mt-1 ${isDark ? 'text-yellow-300' : 'text-yellow-600'}`}>
            Fast richtig! Meintest du: <span className="underline">{answer}</span>
          </p>
        </div>
      )}

      {feedback === 'wrong' && (
        <div className="text-center">
          <span className="text-2xl">❌</span>
          <p className={`text-lg font-semibold mt-1 ${isDark ? 'text-red-300' : 'text-red-600'}`}>
            Falsch. Richtige Antwort:
          </p>
          <p className={`text-xl font-bold mt-1 ${isDark ? 'text-white' : 'text-slate-900'}`}>
            {answer}
          </p>
        </div>
      )}
    </div>
  )
}
