/**
 * Summary + "Configure" button shared by both editor surfaces.
 *
 * The sidebar panel / metabox only ever shows the current configuration as
 * text; every control lives inside the modal opened by the button, so the
 * editor sidebar stays readable no matter how many rules are set.
 */
import { useState } from '@wordpress/element';
import { Button, Modal, Notice } from '@wordpress/components';
import { __ } from '@wordpress/i18n';

import RestrictionFields from './RestrictionFields';
import { isActive, normalize, summarize, warningFor } from './config';

export default function RestrictionPanel( { value, onChange } ) {
	const [ isOpen, setIsOpen ] = useState( false );
	// The modal edits a working copy so "Cancel" really discards the changes.
	const [ draft, setDraft ] = useState( null );

	const config = normalize( value );
	const rows = summarize( config );
	const active = isActive( config );
	const warning = warningFor( config );

	const open = () => {
		setDraft( normalize( value ) );
		setIsOpen( true );
	};

	const close = () => {
		setIsOpen( false );
		setDraft( null );
	};

	const apply = () => {
		onChange( draft );
		close();
	};

	return (
		<div className="arraysubs-restriction-panel">
			{ active ? (
				<dl className="arraysubs-restriction-panel__summary">
					{ rows.map( ( row, index ) => (
						<div
							className="arraysubs-restriction-panel__row"
							key={ `${ row.label }-${ index }` }
						>
							<dt>{ row.label }</dt>
							<dd>{ row.value }</dd>
						</div>
					) ) }
				</dl>
			) : (
				<p className="arraysubs-restriction-panel__empty">
					{ __(
						'No restriction — everyone can view this content.',
						'arraysubs'
					) }
				</p>
			) }

			{ !! warning && (
				<Notice status="warning" isDismissible={ false }>
					{ warning }
				</Notice>
			) }

			<Button
				__next40pxDefaultSize
				variant="secondary"
				className="arraysubs-restriction-panel__configure"
				onClick={ open }
			>
				{ active
					? __( 'Edit restriction', 'arraysubs' )
					: __( 'Configure restriction', 'arraysubs' ) }
			</Button>

			{ isOpen && (
				<Modal
					title={ __( 'Access Restriction', 'arraysubs' ) }
					className="arraysubs-restriction-modal"
					size="large"
					onRequestClose={ close }
				>
					<RestrictionFields
						config={ draft }
						update={ ( patch ) =>
							setDraft( ( prev ) => ( { ...prev, ...patch } ) )
						}
					/>

					<div className="arraysubs-restriction-modal__actions">
						<Button
							__next40pxDefaultSize
							variant="tertiary"
							onClick={ close }
						>
							{ __( 'Cancel', 'arraysubs' ) }
						</Button>
						<Button
							__next40pxDefaultSize
							variant="primary"
							onClick={ apply }
						>
							{ __( 'Apply', 'arraysubs' ) }
						</Button>
					</div>
				</Modal>
			) }
		</div>
	);
}
