import React, { useEffect, useState } from "react";
import { InputNumber } from "./styles";
import { ErrorsInput, IInputProps } from "interfaces";

export interface IInputNumberProps extends IInputProps {
  /** 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 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(), 800);
    return () => clearTimeout(timer);
  }, [shouldValidate]);

  useEffect(() => {
    setVal(value);
  }, [value]);

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

  return (
    <InputNumber
      type="number"
      hasError={hasError}
      disabled={disabled}
      placeholder={placeholder}
      readOnly={readOnly}
      required={required}
      value={val}
      min={min}
      max={max}
      onChange={(e) => {
        setVal(e.target.value);
        onChange(e.target.value);
      }}
      onFocus={() => setShouldValidate(false)}
      onBlur={() => setShouldValidate(true)}
      onKeyPress={(event) => {
        if (!/[0-9]/.test(event.key)) {
          event.preventDefault();
        }
      }}
      styles={styles}
    />
  );
};
