/**
 * WordPress dependencies
 */
import {
	TextControl,
	TextareaControl,
	BaseControl,
} from '@safe-wordpress/components';
import { useInstanceId } from '@safe-wordpress/compose';

/**
 * External dependencies
 */
import clsx from 'clsx';
import type { PostTypeName } from '@nelio-content/types';

/**
 * Internal dependencies
 */
import { PlaceholderInserter } from '../placeholder-inserter';
import './style.scss';

export type TextFieldControlProps = {
	readonly className?: string;
	readonly label: string;
	readonly value: string;
	readonly help?: string;
	readonly type?: PostTypeName;
	readonly hidePlaceholders?: boolean;
	readonly isMultiline?: boolean;
	readonly maxLength?: number;
	readonly onChange: ( value: string ) => void;
};
export const TextFieldControl = (
	props: TextFieldControlProps
): JSX.Element => {
	const {
		className,
		label,
		help,
		value,
		isMultiline = false,
		hidePlaceholders = false,
		type,
		maxLength,
		onChange,
	} = props;
	const instanceId = useInstanceId( TextFieldControl );
	return (
		<BaseControl
			id={ `${ instanceId }` }
			className={ clsx( 'nelio-content-text-field-control', className ) }
			label={ label }
			help={ help }
		>
			{ !! isMultiline ? (
				<TextareaControl value={ value } onChange={ onChange } />
			) : (
				<TextControl
					value={ value }
					maxLength={ maxLength }
					onChange={ onChange }
				/>
			) }
			<PlaceholderInserter
				className="nelio-content-text-field-control__placeholder-button"
				hidden={ hidePlaceholders }
				type={ type }
				onClick={ ( placeholder ) =>
					onChange(
						/[^\s]$/.test( value )
							? `${ value } ${ placeholder }`
							: `${ value }${ placeholder }`
					)
				}
			/>
		</BaseControl>
	);
};
