import React, {useRef, useEffect, useState} from 'react';
import {
  View,
  TextInput,
  StyleSheet,
  TextInputProps,
  NativeSyntheticEvent,
  TextInputKeyPressEventData,
  Platform,
  Keyboard,
  StyleProp,
  ViewStyle,
} from 'react-native';
import {Colors, fontSz, ms} from '../../utils';

type OtpInputProps = {
  codeLength?: number;
  autoFocus?: boolean;
  onCodeFilled: (code: string) => void;
  containerStyle?: StyleProp<ViewStyle>;
};

const OtpInput: React.FC<OtpInputProps> = ({
  codeLength = 4,
  onCodeFilled,
  containerStyle,
  autoFocus,
}) => {
  const [code, setCode] = useState<string[]>(Array(codeLength).fill(''));
  const inputs = useRef<Array<TextInput | null>>([]);

  const handleChange = (text: string, index: number) => {
    if (text.length > 1) {
      // Handle paste
      const chars = text.split('').slice(0, codeLength);
      const newCode = [...code];
      chars.forEach((char, i) => {
        newCode[i] = char;
        if (inputs.current[i]) {inputs.current[i]?.setNativeProps({text: char});}
      });
      setCode(newCode);
      if (chars.length === codeLength) {
        onCodeFilled(chars.join(''));
        Keyboard.dismiss();
      }
    } else {
      const newCode = [...code];
      newCode[index] = text;
      setCode(newCode);
      if (text && index < codeLength - 1) {
        inputs.current[index + 1]?.focus();
      }
      if (newCode.every(char => char !== '')) {
        onCodeFilled(newCode.join(''));
        Keyboard.dismiss();
      }
    }
  };

  const handleKeyPress = (
    e: NativeSyntheticEvent<TextInputKeyPressEventData>,
    index: number,
  ) => {
    if (e.nativeEvent.key === 'Backspace' && code[index] === '' && index > 0) {
      inputs.current[index - 1]?.focus();
    }
  };

  return (
    <View style={[styles.container, containerStyle]}>
      {Array.from({length: codeLength}).map((_, i) => (
        <TextInput
          key={i}
          ref={ref => {
            inputs.current[i] = ref;
          }}
          style={styles.input}
          keyboardType="number-pad"
          maxLength={1}
          returnKeyType="done"
          onChangeText={text => handleChange(text, i)}
          onKeyPress={e => handleKeyPress(e, i)}
          autoFocus={autoFocus ?? i === 0}
          placeholder=""
        />
      ))}
    </View>
  );
};

const styles = StyleSheet.create({
  container: {
    width: '100%',
    flexDirection: 'row',
    justifyContent: 'space-between',
    // columnGap: 20,
  },
  input: {
    textAlign: 'center',
    width: ms(70),
    height: ms(65),
    borderRadius: ms(5),
    borderColor: Colors.neutral20,
    borderWidth: ms(1),
    backgroundColor: 'rgba(179, 179, 179, 0.05)',
    color: Colors.baseBlueText,
    fontFamily: 'Gordita-Medium',
    fontSize: fontSz(24),
    fontWeight: 'bold',
  },
});

export default OtpInput;
