import { useEffect, useRef, useState } from "react";
import { set } from "react-hook-form";
import {
  NativeSyntheticEvent,
  StyleSheet,
  TextInput,
  TextInputKeyPressEventData,
  View,
} from "react-native";
import { LIGHT_THEME } from "../../common/const/theme";

interface MultipleDigitsCodeProps {
  length: number;
  onTextChange?: (value: string) => void;
}

export const MultipleDigitsCode = ({
  length,
  onTextChange,
}: MultipleDigitsCodeProps) => {
  const references = useRef<TextInput[]>([]);
  const [values, setValues] = useState<string[]>(
    Array.from({ length }, () => "")
  );
  const [selectedField, setSelectedField] = useState(0);

  const handleChange = (index: number, value: string) => {
    if (value.length === 0) {
      if (index > 0) {
        setValues((prev) => {
          const newValues = [...prev];
          newValues[index] = value;
          return newValues;
        });
        references.current[index - 1].focus();
      }
      return;
    }
    setValues((prev) => {
      const newValues = [...prev];
      newValues[index] = value;
      return newValues;
    });
    if (index < length - 1) {
      references.current[index + 1].focus();
      setSelectedField(index + 1);
    }
  };

  const handleBackspace = (
    key: NativeSyntheticEvent<TextInputKeyPressEventData>,
    index: number
  ) => {
    if (key.nativeEvent.key === "Backspace") {
      handleChange(index, "");
    }
  };

  const onFocus = (index: number) => {
    setSelectedField(index);
  };

  useEffect(() => {
    if (onTextChange) {
      onTextChange(values.join(""));
    }
  }, [values]);

  return (
    <View style={styles.mainContainer}>
      {Array.from({ length }).map((_, index) => {
        return (
          <TextInput
            ref={(ref) => {
              if (ref && !references.current.includes(ref)) {
                references.current.push(ref);
              }
            }}
            key={`digit-${index}`}
            style={{
              ...styles.input,
              ...(selectedField === index ? styles.focusedInput : {}),
            }}
            maxLength={1}
            keyboardType="number-pad"
            onChangeText={(value) => handleChange(index, value)}
            onKeyPress={(e) => handleBackspace(e, index)}
            onFocus={() => onFocus(index)}
          />
        );
      })}
    </View>
  );
};

const styles = StyleSheet.create({
  mainContainer: {
    height: 70,
    width: "100%",
    display: "flex",
    flexDirection: "row",
    gap: 10,
    justifyContent: "center",
    alignItems: "center",
  },
  input: {
    width: 40,
    height: 50,
    borderWidth: 1,
    borderRadius: 5,
    borderColor: "black",
    textAlign: "center",
  },
  focusedInput: {
    borderColor: LIGHT_THEME.color.primary,
    borderWidth: 2,
  },
});
