import React, { Fragment, useState, useEffect } from 'react';
import Clipboard from '@react-native-clipboard/clipboard';
import { InputContainer, IconCopy } from './styles';
import { AtomIcon } from 'native/atoms/Icon';
import { IInputPropsNative } from 'interfaces';
import { AtomInputText } from 'native/atoms/Input/InputText';
import { AtomTooltip } from 'native/atoms/Tooltip';

export interface IInputCopyProps extends IInputPropsNative {
	value?: string;
	copyMessage?: string;
}

export const MoleculeInputCopy = ({
	value = '',
	copyMessage = 'copied!',
	disabled = false,
	readOnly = false,
	selectTextOnFocus = false,
}: IInputCopyProps) => {
	const [val, setVal] = useState<string>(value);
	const [showTooltip, setShowTooltip] = useState<boolean>(false);
	const [mesagge, setMesagge] = useState<string>(copyMessage);
	const [errorCopy, seterrorCopy] = useState<boolean>(false);

	const fetchCopiedText = async () => {
		try {
			Clipboard.setString(val);
		} catch {
			seterrorCopy(true);
		}
		if (errorCopy) {
			setMesagge('error');
		} else {
			setMesagge(copyMessage);
		}
		setShowTooltip(true);
		setTimeout(() => setShowTooltip(false), 1000);
	};

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

	return (
		<Fragment>
			<AtomTooltip text={mesagge} removeArrow={true} show={showTooltip} />
			<InputContainer>
				<AtomInputText
					selectTextOnFocus={selectTextOnFocus}
					readOnly={readOnly}
					disabled={disabled}
					value={val}
					onChange={(text) => {
						setVal(text);
					}}
					withIcon={true}
				/>
				<IconCopy testID='inputCopy' onPress={() => fetchCopiedText()}>
					<AtomIcon name='copy' size={20} color={'neutral400'} />
				</IconCopy>
			</InputContainer>
		</Fragment>
	);
};
