import { useRef, useEffect } from 'react'
import clsx from 'clsx'
import { motion, AnimatePresence } from 'framer-motion'

type CharStatus = 'pending' | 'correct' | 'error'

interface InputAreaProps {
  userInput: string[]
  charStatuses: CharStatus[]
  isComposing: boolean
  inputLocked: boolean
  lastErrorTimestamp: number | null
  onInputChange: (newInput: string[]) => void
  onCompositionStart: (index: number) => void
  onCompositionEnd: (index: number, value: string) => void
  onPaste: (e: React.ClipboardEvent) => void
}

export function InputArea({
  userInput,
  charStatuses,
  isComposing,
  inputLocked,
  lastErrorTimestamp,
  onInputChange,
  onCompositionStart,
  onCompositionEnd,
  onPaste,
}: InputAreaProps) {
  const inputRefs = useRef<(HTMLInputElement | null)[]>([])

  // 自动聚焦到第一个空输入框
  useEffect(() => {
    if (isComposing || inputLocked) return
    const firstEmptyIndex = userInput.findIndex((char) => !char)
    if (firstEmptyIndex !== -1 && inputRefs.current[firstEmptyIndex]) {
      inputRefs.current[firstEmptyIndex]?.focus()
    }
  }, [userInput, isComposing, inputLocked])

  const handleCharInput = (
    index: number,
    e: React.ChangeEvent<HTMLInputElement>
  ) => {
    if (inputLocked) return

    const value = e.target.value
    const nativeIsComposing =
      typeof (e.nativeEvent as InputEvent).isComposing === 'boolean'
        ? (e.nativeEvent as InputEvent).isComposing
        : false
    const composing = isComposing || nativeIsComposing

    const newInput = [...userInput]

    // 输入法组合期间,只更新当前输入框的值,不做任何跳转
    if (composing) {
      newInput[index] = value
      onInputChange(newInput)
      return
    }

    // 处理多字符输入（连续输入或粘贴）
    if (value.length > 1) {
      const chars = value.split('')
      for (let i = 0; i < chars.length && index + i < userInput.length; i++) {
        newInput[index + i] = chars[i]
      }
      onInputChange(newInput)

      // 聚焦到最后填充的位置的下一个
      const nextIndex = Math.min(index + chars.length, userInput.length - 1)
      inputRefs.current[nextIndex]?.focus()
    } else {
      // 单字符输入
      newInput[index] = value
      onInputChange(newInput)

      // 自动跳转到下一个输入框
      if (value && index < userInput.length - 1) {
        inputRefs.current[index + 1]?.focus()
      }
    }
  }

  const handleKeyDown = (index: number, e: React.KeyboardEvent) => {
    if (inputLocked) return

    // 退格键：清空当前输入并跳转到上一个
    if (e.key === 'Backspace') {
      e.preventDefault()
      const newInput = [...userInput]
      if (newInput[index]) {
        newInput[index] = ''
        onInputChange(newInput)
      } else if (index > 0) {
        newInput[index - 1] = ''
        onInputChange(newInput)
        inputRefs.current[index - 1]?.focus()
      }
    }
    // 左箭头：跳转到上一个
    else if (e.key === 'ArrowLeft' && index > 0) {
      e.preventDefault()
      inputRefs.current[index - 1]?.focus()
    }
    // 右箭头：跳转到下一个
    else if (e.key === 'ArrowRight' && index < userInput.length - 1) {
      e.preventDefault()
      inputRefs.current[index + 1]?.focus()
    }
  }

  return (
    <div className="flex flex-col items-center gap-4 practice-input-area">
      <div className="flex gap-3">
        {userInput.map((char, index) => {
          const status = charStatuses[index] || 'pending'
          const isError = status === 'error'
          const isCorrect = status === 'correct'

          return (
            <motion.div
              key={index}
              className="relative"
              animate={
                isError && lastErrorTimestamp
                  ? {
                      x: [0, -10, 10, -10, 10, 0],
                      transition: { duration: 0.4 },
                    }
                  : {}
              }
            >
              <input
                ref={(el) => (inputRefs.current[index] = el)}
                type="text"
                value={char}
                onChange={(e) => handleCharInput(index, e)}
                onKeyDown={(e) => handleKeyDown(index, e)}
                onCompositionStart={() => onCompositionStart(index)}
                onCompositionEnd={(e) =>
                  onCompositionEnd(index, e.currentTarget.value)
                }
                onPaste={onPaste}
                disabled={inputLocked}
                className={clsx(
                  'w-10 h-12 text-center text-2xl font-medium',
                  'bg-transparent border-b-2 transition-all duration-200',
                  'focus:outline-none',
                  'text-gray-900 dark:text-gray-100',
                  isComposing && 'border-gray-300 dark:border-gray-600 opacity-70',
                  !isComposing && !char && 'border-gray-400 dark:border-gray-500',
                  !isComposing && isCorrect && 'border-green-500',
                  !isComposing && isError && 'border-red-500',
                  inputLocked && 'cursor-not-allowed opacity-50'
                )}
                autoComplete="off"
                autoCorrect="off"
                autoCapitalize="off"
                spellCheck="false"
              />
            </motion.div>
          )
        })}
      </div>

      {/* 输入锁定提示 */}
      <AnimatePresence>
        {inputLocked && (
          <motion.div
            initial={{ opacity: 0, y: -10 }}
            animate={{ opacity: 1, y: 0 }}
            exit={{ opacity: 0, y: -10 }}
            className="text-sm text-gray-500 dark:text-gray-400"
          >
            答案显示中，输入已锁定
          </motion.div>
        )}
      </AnimatePresence>
    </div>
  )
}
