import { useState, useRef, useEffect } from 'react'
import { XStack, Input } from 'tamagui'

export const CodeInput = ({ onChange, codeLength }) => {
  const [inputValues, setInputValues] = useState(Array(codeLength).fill(''))
  const inputRefs = useRef<(Input | null)[]>([])

  useEffect(() => {
    const newValue = inputValues.join('')
    onChange(newValue)
  }, [inputValues, onChange])

  const handleChange = (val, index) => {
    if (/^\d*$/.test(val)) {
      const newInputValues = [...inputValues]
      newInputValues[index] = val
      setInputValues(newInputValues)

      if (val && index < codeLength - 1) {
        inputRefs.current[index + 1]?.focus()
      }
    }
  }

  const handleKeyPress = (e, index) => {
    if (e.nativeEvent.key === 'Backspace' && !inputValues[index] && index > 0) {
      inputRefs.current[index - 1]?.focus()
    }
  }

  return (
    <XStack gap="$2">
      {inputValues.map((val, index) => (
        <Input
          key={index}
          ref={(el) => {
            inputRefs.current[index] = el
          }}
          value={val}
          onChangeText={(text) => handleChange(text, index)}
          onKeyPress={(e) => handleKeyPress(e, index)}
          keyboardType="numeric"
          maxLength={1}
          textAlign="center"
          w="$5"
          h="$6"
        />
      ))}
    </XStack>
  )
}
