import React, { useEffect, useState } from 'react';
import { InputContainer, InputPassword, ShowPassword } from './styles';
import { AtomIcon } from 'react/atoms/Icon';
import { IInputProps, ErrorsInput } from 'interfaces';

export interface IInputPasswordProps extends IInputProps {
  value?: string;
}

export const AtomInputPassword = ({
  disabled = false,
  placeholder = '',
  required = false,
  value = '',
  regex,
  styles = {},
  onChange = () =>{},
  errorCallback = () => {}
}: IInputPasswordProps) => {

  const [val, setVal] = useState<string>(value);
  const [showPassword, setShowPassword] = useState<boolean>(false);
  const [hasError, setHasError] = useState<boolean>(false);
  const [shouldValidate, setShouldValidate] = useState<boolean>(false);
  const [passwordRegex, setpasswordRegex] = useState<RegExp | null>((regex ? new RegExp(regex) : null));

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

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

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

  const validatePassword = () => {
    setHasError(false);
    
    if (shouldValidate && passwordRegex) {
      if (!passwordRegex.test(val)) {        
        setHasError(true);
        errorCallback('regExp');
      }
    }else{
      setHasError(false);
    }; 
    validateRequired()
    setShouldValidate(false);
  }
  
  useEffect(() => {
    validateRequired()
  }, [val, required])

  return (
    <>
      <InputContainer>
        <InputPassword
          type={!showPassword? 'password' : 'text' }
          disabled={disabled}
          placeholder={placeholder}
          hasError={hasError}
          required={required}
          value={val}
          onChange={(e) => {
            setShouldValidate(true)
            setVal(e.target.value)
            onChange(e.target.value);
          }}
          styles={styles}
        />
        <ShowPassword
          id='showPassword'
          onClick={() => {
            if (!disabled) {
                setShowPassword(!showPassword);
            }
          }}>
          {
            (!showPassword)
              ? <AtomIcon icon='eye-off' size={20} color={disabled ? 'neutral400' : 'neutral600'} />
              : <AtomIcon icon='eye-on' size={20} color={disabled ? 'neutral400' : 'neutral600'} />
          }
        </ShowPassword>
      </InputContainer>
    </>
  )
};