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

export interface IInputEmailProps extends IInputPropsNative {
  value?: string;
}

export const AtomInputEmail = ({
  disabled = false,
  placeholder = 'Email',
  readOnly = false,
  required = false,
  value='',
  regex,
  styles = {},
  onChange = () => {},
  errorCallback = () => {}
}: IInputEmailProps) => {
  const [val, setVal] = useState<string>(value)
  const [hasError, setHasError] = useState<boolean>(false)
  const [shouldValidate, setShouldValidate] = useState<boolean>(false)
  const [mailRegex, setMailRegex] = useState<RegExp | null>((regex ? new RegExp(regex) : null));
  const emailRegex: RegExp = /^[a-zA-Z0-9.!#$%&'*+?/=?^_`{|}~-]+@[a-zA-Z0-9-]+(?:\.[a-zA-Z0-9-]{2,3}){1,2}$/

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

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

  const validateRequired = () => {
    setHasError(false);
    if (required && val == '') {
      let error: ErrorsInput = null;
      setHasError(true);
      error = 'required';
      error && errorCallback && errorCallback(error)
    }
  }

  const validateEmail = () => {
    validateRequired()
    if (shouldValidate) {
      if (mailRegex && val) {
        if (!mailRegex.test(val)) {
          setHasError(true);
          errorCallback('regExp')
        }
      };
      if (!emailRegex.test(val)) {
        setHasError(true);
        errorCallback('regExp')
      }
    }
  }

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

  
  return (
    <InputEmail
      testID='TestInputEmail'
      hasError={hasError}
      disabled={disabled}
      placeholder={placeholder}
      editable={!readOnly}
      value={val}
      onChangeText={(value: string) => {
        setShouldValidate(true)
        setVal(value)
        onChange(value)
      }}
      placeholderTextColor={theme.neutral500}
      styles={styles}
    />
  );
};
