import {Box, Center, HStack, Input, Pressable, Text} from 'native-base';
import {useEffect, useRef, useState} from 'react';
import {
  TextInput,
  NativeSyntheticEvent,
  TextInputChangeEventData,
} from 'react-native';

function RenderCell(props: {
  index: number;
  text: string | number;
  maxIndex: number;
  isFocus: boolean;
  disabled: boolean;
  rest: any;
}) {
  const display: string = props.text ? props.text.toString() : '';

  const [toggle, setToggle] = useState(true);

  useEffect(() => {
    if (props.isFocus === false) return;

    let timer = setInterval(() => {
      setToggle(!toggle);
    }, 500);
    return () => {
      clearInterval(timer);
    };
  });

  return (
    <Pressable
      {...props.rest}
      w={10}
      h={10}
      borderColor={props.isFocus ? 'primary.300' : 'black.100'}
      backgroundColor={
        props.disabled ? 'black.300' : props.isFocus ? '#ff9b7933' : null
      }
      borderWidth={1}
      borderRadius={5}>
      <Center w={'100%'} h={'100%'}>
        <Text
          fontSize={'2xl'}
          color={props.disabled ? 'white.100' : 'white.900'}
          {...props.rest}>
          {props.isFocus ? (toggle ? '|' : '') : display}
        </Text>
      </Center>
    </Pressable>
  );
}

function ConfirmationCodeField(props: {
  cellCount: number;
  charType: 'number' | 'letter';
  onFinish?: Function;
  onChange?: Function;
  disabled?: boolean;
  rest?: any;
}) {
  const [values, setValues] = useState({input: ''});
  const [isFocus, setFocus] = useState(false);

  const inputRef = useRef<TextInput>(null);

  return (
    <Box {...props.rest}>
      <TextInput
        autoFocus
        ref={inputRef}
        value={values.input}
        keyboardType={props.charType === 'number' ? 'numeric' : 'default'}
        onFocus={() => setFocus(true)}
        onBlur={() => setFocus(false)}
        editable={!props.disabled}
        onChange={(event: NativeSyntheticEvent<TextInputChangeEventData>) => {
          let text = event.nativeEvent.text;
          let vals = {...values};

          if (props.charType === 'number')
            vals.input = text.replace(/[^0-9]/g, '');
          else if (props.charType === 'letter') vals.input = text;

          vals.input = vals.input.slice(0, props.cellCount);

          setValues(vals);

          if (props.onChange) props.onChange(vals.input);

          if (vals.input.length === props.cellCount) {
            if (inputRef.current !== null) {
              inputRef.current.blur();
              if (props.onFinish) props.onFinish(vals.input);
            }
          }
        }}
        style={{
          position: 'absolute',
          opacity: 0,
          width: 1,
          height: 1,

          padding: 0,
          margin: 0,
        }}
      />
      <HStack space={3} justifyContent="center">
        {(() => {
          let cells = [];
          for (let i = 0; i < props.cellCount; i++) {
            cells.push(
              <RenderCell
                key={'ConfirmationCodeFieldCell' + i}
                index={i}
                isFocus={isFocus === true ? values.input.length === i : false}
                text={values.input[i]}
                maxIndex={props.cellCount}
                disabled={props.disabled || false}
                rest={{
                  onPress: !props.disabled
                    ? () => {
                        let vals = {...values};
                        vals.input = vals.input.slice(0, i);
                        setValues(vals);

                        if (props.onChange) props.onChange(vals.input);

                        if (inputRef.current !== null) {
                          inputRef.current.focus();
                        }
                      }
                    : undefined,
                }}
              />,
            );
          }
          return cells;
        })()}
      </HStack>
    </Box>
  );
}

export default ConfirmationCodeField;
