import React, { useEffect, useState } from 'react';
import { theme } from 'data/dataMx';
import { ErrorsInput, IInputPropsNative } from 'interfaces';
import { InputContainer, InputPassword, ShowPassword } from './styles';
import { AtomIcon } from 'native/atoms/Icon';

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

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

  const [val, setVal] = useState<string>(value);
  const [hasError, setHasError] = useState<boolean>(false);
  const [showPassword, setShowPassword] = useState<boolean>(true);
  const [shouldValidate, setShouldValidate] = useState<boolean>(false);
  const [passwordRegex, setRegex] = 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
          testID='inputPassword'
          secureTextEntry={(showPassword)}
          disabled={disabled}
          placeholder={placeholder}
          hasError={hasError}
          value={val.toString()}
          onChangeText={(text: string) => {
            setShouldValidate(true)
            setVal(text)
            onChange(text)
          }}
          placeholderTextColor={theme.neutral500}
          styles={styles}
        />
        <ShowPassword
          testID='showPassword'
          onPress={() => {
            if (!disabled) {
              if (showPassword == true) {
                setShowPassword(false);
              }
              else {
                setShowPassword(true);
              }
            }
          }}>
          {
            (showPassword)
              ? <AtomIcon name='eye-off' size={20} color={disabled ? 'neutral400' : 'neutral600'} />
              : <AtomIcon name='eye-on' size={20} color={disabled ? 'neutral400' : 'neutral600'} />
          }
        </ShowPassword>
      </InputContainer>
    </>
  )
};