import React, { useEffect, useState } from "react";
import { theme } from "data/dataMx";
import { InputNumber } from "./styles";
import { ErrorsInput, IInputPropsNative } from "interfaces";

export interface IInputNumberProps extends IInputPropsNative {
  /** Initial value */
  value?: string;
  /** Min value */
  min?: string;
  /** Max value */
  max?: string;
}

export const AtomInputNumber = ({
  disabled = false,
  placeholder = "",
  readOnly = false,
  required = false,
  regex = "^[0-9]+$",
  value = "",
  min,
  max,
  onChange = () => {},
  errorCallback = () => {},
  styles = {},
}: IInputNumberProps) => {
  const [val, setVal] = useState<string>(value);
  const [hasError, setHasError] = useState<boolean>(false);
  const [shouldValidate, setShouldValidate] = useState<boolean>(false);
  const [numberRegex, setNumberRegex] = useState<RegExp | null>(
    regex ? new RegExp(regex) : null
  );
  const [focus, setFocus] = useState<boolean>(false);

  useEffect(() => {
    setVal(value.replace(/[^0-9]/g, ""));
  }, [value]);
  const validateRequired = () => {
    if (required && val == "") {
      let error: ErrorsInput = null;
      setHasError(true);
      error = "required";
      error && errorCallback && errorCallback(error);
    } else {
      setHasError(false);
    }
  };
  const validateNumber = () => {
    setHasError(false);
    let error: ErrorsInput = null;
    const intValue = parseInt(val);
    if (intValue < parseInt(min!)) {
      setHasError(true);
      error = "min";
    }
    if (intValue > parseInt(max!)) {
      setHasError(true);
      error = "max";
    }
    if (numberRegex && val) {
      if (!numberRegex.test(val)) {
        setHasError(true);
        error = "regExp";
      }
    } else {
      setHasError(false);
    }
    validateRequired();
    error && errorCallback && errorCallback(error);
    setShouldValidate(false);
  };

  useEffect(() => {
    const timer = setTimeout(() => validateNumber(), 200);
    return () => clearTimeout(timer);
  }, [shouldValidate]);

  useEffect(() => {
    validateRequired();
  }, [val, required]);

  return (
    <InputNumber
      testID="TestInputNumber"
      hasError={hasError}
      disabled={disabled}
      placeholder={placeholder}
      editable={!readOnly}
      value={val}
      focus={focus}
      keyboardType="numeric"
      onChangeText={(value: string) => {
        const valueNumber = value.replace(/[^0-9]/g, "");
        setVal(valueNumber);
        onChange(valueNumber);
        setShouldValidate(true);
      }}
      placeholderTextColor={theme.neutral500}
      onFocus={() => {
        setFocus(true);
      }}
      onBlur={() => {
        setFocus(false);
      }}
      styles={styles}
    />
  );
};
