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

export interface IInputTextProps extends IInputProps {
  value?: string;
  withIcon?: boolean;
}

export const AtomInputText = ({
  disabled = false,
  placeholder = "",
  readOnly = false,
  required = false,
  value = "",
  withIcon = false,
  onChange = () => {},
  errorCallback = () => {},
  styles,
  regex,
}: IInputTextProps) => {
  const [val, setVal] = useState<string>(value);
  const [shouldValidate, setShouldValidate] = useState<boolean>(true);
  const [hasError, setHasError] = useState<boolean>(false);
  const [textRegex, setTextRegex] = 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 validateText = () => {
    setHasError(false);
    if (shouldValidate && textRegex) {
      if (!textRegex.test(val)) {
        setHasError(true);
        errorCallback("regExp");
      }
    } else {
      setHasError(false);
    }
    validateRequired();
  };

  useEffect(() => {
    const timer = setTimeout(() => validateText(), 800);
    return () => clearTimeout(timer);
  }, [val]);

  useEffect(() => {
    setVal(value);
    setTextRegex(regex ? new RegExp(regex) : null);
  }, [value]);

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

  return (
    <InputBase
      withIcon={withIcon}
      disabled={disabled}
      placeholder={placeholder}
      readOnly={readOnly}
      required={required}
      value={val}
      hasError={hasError}
      onChange={(e) => {
        setShouldValidate(true);
        setVal(e.target.value);
        onChange(e.target.value);
      }}
      styles={styles}
    />
  );
};
