/**
 * Reusable corner-radius control for style-schema `boxRadius` fields.
 * Mini popup: radius value + per-corner on/off toggles.
 */
import {
	BaseControl,
	Dropdown,
	__experimentalDropdownContentWrapper as DropdownContentWrapper,
} from '@wordpress/components';
import { __ } from '@wordpress/i18n';
import {
	DEFAULT_BORDER_RADIUS,
	boxRadiusKeys,
	isRadiusCornerOn,
	radiusCornerValue,
	resolveBoxRadiusState,
} from '../styleFieldRadius';
import FlexibleUnitControl from './FlexibleUnitControl';
const CORNER_DEFS = [
	{
		id: 'topLeft',
		label: __( 'Top left', 'joc-blockora-morph' ),
		short: 'TL',
	},
	{
		id: 'topRight',
		label: __( 'Top right', 'joc-blockora-morph' ),
		short: 'TR',
	},
	{
		id: 'bottomRight',
		label: __( 'Bottom right', 'joc-blockora-morph' ),
		short: 'BR',
	},
	{
		id: 'bottomLeft',
		label: __( 'Bottom left', 'joc-blockora-morph' ),
		short: 'BL',
	},
];

/**
 * @param {object}   props
 * @param {object}   props.field
 * @param {object}   [props.values]
 * @param {Function} props.onChange  (patch: Record<string, string>) => void
 */
export default function BoxRadiusField( { field, values = {}, onChange } ) {
	const keys = boxRadiusKeys( field );
	const inheritWhenOff = Boolean( field?.inheritWhenOff );
	const allowEmpty = Boolean( field?.allowEmpty || inheritWhenOff );
	const valueOpts = { allowEmpty, inheritWhenOff, zeroIsOn: inheritWhenOff };
	const storeOpts = {
		emptyWhenOff: inheritWhenOff,
		allowEmpty,
	};
	const { radius, corners } = resolveBoxRadiusState(
		values,
		keys,
		valueOpts
	);

	const emit = ( next ) => {
		let r = next.radius != null ? next.radius : radius;
		if ( ! allowEmpty ) {
			r = r || DEFAULT_BORDER_RADIUS;
		}
		const nextCorners = {
			topLeft: next.topLeft != null ? next.topLeft : corners.topLeft,
			topRight: next.topRight != null ? next.topRight : corners.topRight,
			bottomRight:
				next.bottomRight != null ? next.bottomRight : corners.bottomRight,
			bottomLeft:
				next.bottomLeft != null ? next.bottomLeft : corners.bottomLeft,
		};
		const radiusIsSet =
			String( r ?? '' ).trim() !== '' ||
			isRadiusCornerOn( r, { zeroIsOn: inheritWhenOff } );
		// Radius edits with every corner off used to keep writing 0 — turn on.
		if (
			next.radius != null &&
			radiusIsSet &&
			! nextCorners.topLeft &&
			! nextCorners.topRight &&
			! nextCorners.bottomRight &&
			! nextCorners.bottomLeft
		) {
			nextCorners.topLeft = true;
			nextCorners.topRight = true;
			nextCorners.bottomRight = true;
			nextCorners.bottomLeft = true;
		}
		const tl = radiusCornerValue( nextCorners.topLeft, r, storeOpts );
		const tr = radiusCornerValue( nextCorners.topRight, r, storeOpts );
		const br = radiusCornerValue( nextCorners.bottomRight, r, storeOpts );
		const bl = radiusCornerValue( nextCorners.bottomLeft, r, storeOpts );
		const allOn =
			nextCorners.topLeft &&
			nextCorners.topRight &&
			nextCorners.bottomRight &&
			nextCorners.bottomLeft;
		const allValue = allOn
			? allowEmpty
				? String( r ?? '' ).trim()
				: r || DEFAULT_BORDER_RADIUS
			: `${ tl } ${ tr } ${ br } ${ bl }`.trim();
		onChange( {
			[ keys.all ]: allValue,
			[ keys.topLeft ]: tl,
			[ keys.topRight ]: tr,
			[ keys.bottomRight ]: br,
			[ keys.bottomLeft ]: bl,
		} );
	};

	const previewStyle = {
		borderRadius: `${ corners.topLeft ? radius || '0' : '0' } ${
			corners.topRight ? radius || '0' : '0'
		} ${ corners.bottomRight ? radius || '0' : '0' } ${
			corners.bottomLeft ? radius || '0' : '0'
		}`,
	};

	const cornerSummary = CORNER_DEFS.filter( ( corner ) => corners[ corner.id ] )
		.map( ( corner ) => corner.short )
		.join( '·' );
	const summary = cornerSummary
		? `${ radius || '0' } · ${ cornerSummary }`
		: inheritWhenOff || allowEmpty
		? __( 'Inherit', 'joc-blockora-morph' )
		: __( 'None', 'joc-blockora-morph' );

	return (
		<div className="bm-style-field bm-style-field--box-radius bm-box-radius">
			<span className="bm-box-radius__label">
				{ field.label || __( 'Corner radius', 'joc-blockora-morph' ) }
			</span>
			<Dropdown
				className="bm-box-radius__dropdown"
				popoverProps={ {
					placement: 'bottom-start',
					offset: 8,
				} }
				renderToggle={ ( { isOpen, onToggle } ) => (
					<button
						type="button"
						className={
							'bm-box-radius__toggle' + ( isOpen ? ' is-open' : '' )
						}
						onClick={ onToggle }
						aria-expanded={ isOpen }
						aria-label={ __( 'Edit corner radius', 'joc-blockora-morph' ) }
					>
						<span
							className="bm-box-radius__preview"
							style={ previewStyle }
							aria-hidden="true"
						/>
						<span className="bm-box-radius__meta">
							<span className="bm-box-radius__meta-title">
								{ __( 'Corner radius', 'joc-blockora-morph' ) }
							</span>
							<span className="bm-box-radius__meta-sub">
								{ summary }
							</span>
						</span>
					</button>
				) }
				renderContent={ () => (
					<DropdownContentWrapper paddingSize="medium">
						<div className="bm-box-radius__popover">
							<p className="bm-box-radius__popover-title">
								{ field.label ||
									__( 'Corner radius', 'joc-blockora-morph' ) }
							</p>
							<FlexibleUnitControl
								label={ __( 'Radius', 'joc-blockora-morph' ) }
								value={ radius }
								onChange={ ( next ) =>
									emit( {
										radius: allowEmpty
											? next || ''
											: next || DEFAULT_BORDER_RADIUS,
									} )
								}
								units={ [
									{ value: 'px', label: 'px', default: 8 },
									{ value: 'em', label: 'em', default: 0.5 },
									{ value: 'rem', label: 'rem', default: 0.5 },
									{ value: '%', label: '%', default: 50 },
								] }
							/>
							<BaseControl
								label={ __( 'Corners', 'joc-blockora-morph' ) }
								__nextHasNoMarginBottom
							>
								<div
									className="bm-box-sides-pad bm-box-sides-pad--corners"
									role="group"
									aria-label={ __(
										'Border radius corners',
										'joc-blockora-morph'
									) }
								>
									{ CORNER_DEFS.map( ( corner ) => (
										<button
											key={ corner.id }
											type="button"
											className={
												`bm-box-sides-pad__cell bm-box-sides-pad__cell--${ corner.id }` +
												( corners[ corner.id ]
													? ' is-on'
													: '' )
											}
											aria-pressed={ corners[ corner.id ] }
											aria-label={ corner.label }
											onClick={ () =>
												emit( {
													[ corner.id ]:
														! corners[ corner.id ],
												} )
											}
										>
											{ corner.short }
										</button>
									) ) }
									<span
										className="bm-box-sides-pad__preview"
										style={ previewStyle }
										aria-hidden="true"
									/>
								</div>
							</BaseControl>
						</div>
					</DropdownContentWrapper>
				) }
			/>
		</div>
	);
}
