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

export interface IInputTextProps extends IInputPropsNative {
	value?: string;
	withIcon?: boolean;
	inputMaxLength?: number;
}

export const AtomInputText = ({
	disabled,
	readOnly,
	selectTextOnFocus,
	placeholder = '',
	value = '',
	inputMaxLength,
	required,
	withIcon = false,
	onChange = () => {},
	errorCallback = () => {},
	regex,
	styles = {},
	keyboardType,
}: IInputTextProps) => {
	const [val, setVal] = useState<string>(value);
	const [focus, setFocus] = useState<boolean>(false);
	const [shouldValidate, setShouldValidate] = useState<boolean>(false);
	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 = () => {
		if (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);
	}, [value]);

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

	return (
		<Fragment>
			<InputBase
				disabled={disabled}
				placeholder={placeholder}
				editable={!readOnly}
				focus={focus}
				value={val}
				hasError={hasError}
				onChangeText={(text: string) => {
					setVal(text);
					onChange(text);
				}}
				testID={'input'}
				onFocus={() => {
					setFocus(true);
				}}
				onBlur={() => {
					setFocus(false);
				}}
				withIcon={withIcon}
				maxLength={inputMaxLength}
				placeholderTextColor={theme.neutral500}
				styles={styles}
				selectTextOnFocus={selectTextOnFocus}
				keyboardType={keyboardType}
			/>
		</Fragment>
	);
};
