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

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

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

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

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

type HeaderControlProps = {
	readonly item: WebhookHeader;
	readonly hidePlaceholders?: boolean;
	readonly type?: PostTypeName;
	readonly onChange: ( value: WebhookHeader ) => void;
	readonly onRemove: () => void;
};
const HeaderControl = ( props: HeaderControlProps ): 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( 'Header name', 'text', 'nelio-content' ) }
				onChange={ ( value ) => onChange( { ...item, key: value } ) }
			/>
			<TextFieldControl
				value={ item.value }
				hidePlaceholders={ hidePlaceholders }
				type={ type }
				label={ _x( 'Header value', 'text', 'nelio-content' ) }
				onChange={ ( value ) => onChange( { ...item, value } ) }
			/>
			<Button
				className="nelio-content-webhook-settings-control__field-remove-button"
				icon="dismiss"
				onClick={ onRemove }
			/>
		</div>
	);
};
