/**
 * WordPress dependencies
 */
import {
	__experimentalInputControlSuffixWrapper as InputControlSuffixWrapper,
	Button,
} from '@wordpress/components';
import { useCallback, useState } from '@wordpress/element';
import { __ } from '@wordpress/i18n';
import { seen, unseen } from '@wordpress/icons';
/**
 * Internal dependencies
 */
import ValidatedText from './utils/validated-input';
import type { DataFormControlProps } from '../../types';

export default function Password< Item >( {
	data,
	field,
	onChange,
	hideLabelFromVision,
	markWhenOptional,
	validity,
}: DataFormControlProps< Item > ) {
	const [ isVisible, setIsVisible ] = useState( false );

	const toggleVisibility = useCallback( () => {
		setIsVisible( ( prev ) => ! prev );
	}, [] );

	return (
		<ValidatedText
			{ ...{
				data,
				field,
				onChange,
				hideLabelFromVision,
				markWhenOptional,
				validity,
				type: isVisible ? 'text' : 'password',
				suffix: (
					<InputControlSuffixWrapper variant="control">
						<Button
							icon={ isVisible ? unseen : seen }
							onClick={ toggleVisibility }
							size="small"
							label={
								isVisible
									? __( 'Hide password' )
									: __( 'Show password' )
							}
						/>
					</InputControlSuffixWrapper>
				),
			} }
		/>
	);
}
