/**
 * WordPress dependencies
 */
import { BaseControl, Button } from '@safe-wordpress/components';
import { _x } from '@safe-wordpress/i18n';

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

/**
 * Internal dependencies
 */
import { TextFieldControl } from '../text-field-control';

export type FormDataKeyValuesFieldControlProps = {
	readonly label: string;
	readonly items: ReadonlyArray< WebhookFormField >;
	readonly hidePlaceholders?: boolean;
	readonly type?: PostTypeName;
	readonly onChange: ( value: ReadonlyArray< WebhookFormField > ) => void;
};
export const FormDataKeyValuesFieldControl = (
	props: FormDataKeyValuesFieldControlProps
): JSX.Element => {
	const { label, items, hidePlaceholders, type, onChange } = props;

	return (
		<BaseControl
			className="nelio-content-webhook-settings-control__field-list"
			label={ label }
			id="nelio-content-form-data-fields"
		>
			<div className="nelio-content-webhook-settings-control__field-inner-list">
				{ items.map( ( item, index ) => (
					<FormDataKeyValueControl
						key={ index }
						item={ item }
						hidePlaceholders={ hidePlaceholders }
						type={ type }
						onChange={ ( value ) =>
							onChange(
								[ ...items ].map( ( i, idx ) =>
									idx === index ? value : i
								)
							)
						}
						onRemove={ () =>
							onChange(
								[ ...items ].filter(
									( _: WebhookFormField, idx: number ) =>
										idx !== index
								)
							)
						}
					/>
				) ) }
			</div>
			<Button
				className="nelio-content-webhook-settings-control__field-add-button"
				variant="link"
				onClick={ () =>
					onChange( [ ...items, { key: '', value: '' } ] )
				}
			>
				{ _x( 'Add Field', 'command', 'nelio-forms-premium' ) }
			</Button>
		</BaseControl>
	);
};

type FormDataKeyValueControlProps = {
	readonly item: WebhookFormField;
	readonly hidePlaceholders?: boolean;
	readonly type?: PostTypeName;
	readonly onChange: ( value: WebhookFormField ) => void;
	readonly onRemove: () => void;
};
const FormDataKeyValueControl = (
	props: FormDataKeyValueControlProps
): JSX.Element => {
	const { item, hidePlaceholders, type, onChange, onRemove } = props;

	return (
		<div className="nelio-content-webhook-settings-control__field-item">
			<TextFieldControl
				value={ item.key }
				hidePlaceholders={ hidePlaceholders }
				type={ type }
				label={ _x( 'Key', 'text', 'nelio-forms-premium' ) }
				onChange={ ( value ) => onChange( { ...item, key: value } ) }
			/>
			<TextFieldControl
				value={ item.value }
				hidePlaceholders={ hidePlaceholders }
				type={ type }
				label={ _x( 'Value', 'text', 'nelio-forms-premium' ) }
				onChange={ ( value ) => onChange( { ...item, value } ) }
			/>
			<Button
				className="nelio-content-webhook-settings-control__field-remove-button"
				icon="dismiss"
				onClick={ onRemove }
			/>
		</div>
	);
};
