import { Input, XStack } from '@junwon/aesthetics'
import { useRef } from 'react'

interface CodeInputProps {
  codeLength: number
  inputValues: string[]
  setInputValues: (values: string[]) => void
}

export const CodeInput = ({ codeLength, inputValues, setInputValues }: CodeInputProps) => {
  const inputRefs = useRef<(any | null)[]>([])

  const handleChange = (val: string, index: number) => {
    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: any, index: number) => {
    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="number-pad"
          maxLength={1}
          fos="$8"
          ta="center"
          w="$5"
          h="$6"
          bw={2}
          br="$4"
          focusStyle={{
            bg: '$blue2',
            boc: '$blue8',
          }}
        />
      ))}
    </XStack>
  )
}
