import { __ } from '@wordpress/i18n';
import { PanelBody, ButtonGroup, Button } from '@wordpress/components';
import { link, linkOff, rotateRight } from '@wordpress/icons';
import { useDevice } from '../../controls/DeviceContext';
import { getResponsivePlaceholder } from '../../controls/responsiveValueUtils';
import IconStyle from '../icons/IconStyle';
import IconSettings from '../../settings/IconSettings';
import UnitValueControl from '../../controls/UnitValueControl';

// Normalise a per-device iconSize value into { width, height, isLinked }.
// Accepts legacy string form (e.g. "20px") and treats it as both width & height.
const toSize = ( raw ) => {
	if ( raw == null || raw === '' ) {
		return { width: '', height: '', isLinked: true };
	}
	if ( typeof raw === 'string' ) {
		return { width: raw, height: raw, isLinked: true };
	}
	if ( typeof raw === 'object' ) {
		const width = typeof raw.width === 'string' ? raw.width : '';
		const height = typeof raw.height === 'string' ? raw.height : '';
		const isLinked = typeof raw.isLinked === 'boolean'
			? raw.isLinked
			// If the stored object has no explicit link flag, consider it linked
			// only when width and height agree (or either is empty).
			: ( width === height || width === '' || height === '' );
		return { width, height, isLinked };
	}
	return { width: '', height: '', isLinked: true };
};

export default function IconSizeControl( {
	attributes,
	setAttributes,
	showPosition = true,
	activeStyleTab = 'icon',
	showIconSelection = true,
	showColorControls = true,
	showIconReset = true,
	showPreview,
} ) {
	const { activeDevice } = useDevice();
	const isHoverTab = activeStyleTab === 'iconHover';
	const sizeAttribute = isHoverTab ? 'iconSize__hover' : 'iconSize';
	const emptyResponsiveValue = { desktop: '', tablet: '', mobile: '' };
	const shouldShowPreview =
		typeof showPreview === 'boolean'
			? showPreview
			: ( showIconSelection || showColorControls );
	const shouldRenderIconSettings =
		showIconSelection || showColorControls || shouldShowPreview;

	const baseIconSize = attributes.iconSize || { ...emptyResponsiveValue };
	const iconSize = attributes[ sizeAttribute ] || { ...emptyResponsiveValue };

	const deviceSize = toSize( iconSize[ activeDevice ] );
	const { width, height, isLinked } = deviceSize;

	const pickSide = ( raw, side ) => {
		const normalised = toSize( raw );
		return normalised[ side ] || '';
	};

	const widthPlaceholder = getResponsivePlaceholder( {
		values: isHoverTab ? iconSize : baseIconSize,
		activeDevice,
		selector: ( value ) => pickSide( value, 'width' ),
		fallback: isHoverTab ? pickSide( baseIconSize[ activeDevice ], 'width' ) : 'e.g., 16px',
	} );
	const heightPlaceholder = getResponsivePlaceholder( {
		values: isHoverTab ? iconSize : baseIconSize,
		activeDevice,
		selector: ( value ) => pickSide( value, 'height' ),
		fallback: isHoverTab ? pickSide( baseIconSize[ activeDevice ], 'height' ) : 'e.g., 16px',
	} );
	const linkedPlaceholder = getResponsivePlaceholder( {
		values: isHoverTab ? iconSize : baseIconSize,
		activeDevice,
		selector: ( value ) => {
			const s = toSize( value );
			return s.width || s.height || '';
		},
		fallback: isHoverTab ? ( pickSide( baseIconSize[ activeDevice ], 'width' ) || pickSide( baseIconSize[ activeDevice ], 'height' ) ) : 'e.g., 16px, 1.2em',
	} );

	const helpText = isHoverTab
		? __( 'Leave empty to inherit the Icon size.', 'axcelersblocks' )
		: __( 'Examples: 16px, 1.2em', 'axcelersblocks' );

	const writeSize = ( next ) => {
		setAttributes( {
			[ sizeAttribute ]: {
				...iconSize,
				[ activeDevice ]: { width: '', height: '', isLinked: true, ...next },
			},
		} );
	};

	const handleToggleLink = () => {
		const willBeLinked = ! isLinked;
		if ( willBeLinked ) {
			const seed = width || height || '';
			writeSize( { width: seed, height: seed, isLinked: true } );
		} else {
			writeSize( { width, height: height || width, isLinked: false } );
		}
	};

	const handleReset = () => {
		writeSize( { width: '', height: '', isLinked: true } );
	};

	const handleLinkedChange = ( value ) => {
		writeSize( { width: value, height: value, isLinked: true } );
	};

	const handleWidthChange = ( value ) => {
		writeSize( { width: value, height: isLinked ? value : height, isLinked } );
	};

	const handleHeightChange = ( value ) => {
		writeSize( { width: isLinked ? value : width, height: value, isLinked } );
	};

	return (
		<PanelBody
			className="icon-controls-wrapper"
			title={
				<div style={ { display: 'flex', justifyContent: 'space-between', alignItems: 'center' } }>
					<span className="axb-title-with-badge title">
						<IconStyle />
						{ __( 'Icon', 'axcelersblocks' ) }
					</span>
				</div>
			}
			initialOpen={ false }
		>
			{ shouldRenderIconSettings && (
				<>
					<div className="axcelersblocks-settings-section">
						<IconSettings
							attributes={ attributes }
							setAttributes={ setAttributes }
							showPosition={ showPosition }
							activeStyleTab={ activeStyleTab }
							showLibraryControls={ showIconSelection }
							showColorControls={ showColorControls }
							showReset={ showIconReset }
							showPreview={ shouldShowPreview }
						/>
					</div>

					<hr className="axcelersblocks-divider" />
				</>
			) }

			<div className="axcelersblocks-spacing-header">
				<strong>{ __( 'Icon Size', 'axcelersblocks' ) }</strong>
				<ButtonGroup>
					<Button
						icon={ isLinked ? link : linkOff }
						isPressed={ isLinked }
						onClick={ handleToggleLink }
						label={ isLinked ? __( 'Unlink width & height', 'axcelersblocks' ) : __( 'Link width & height', 'axcelersblocks' ) }
					/>
					<Button
						icon={ rotateRight }
						onClick={ handleReset }
						label={ __( 'Reset', 'axcelersblocks' ) }
						showTooltip={ true }
					/>
				</ButtonGroup>
			</div>

			<div
				className={
					isLinked
						? 'axcelersblocks-icon-size-fields axcelersblocks-icon-size-fields--linked'
						: 'axcelersblocks-icon-size-fields axcelersblocks-icon-size-fields--split'
				}
			>
				{ isLinked ? (
					<UnitValueControl
						label={ __( 'Size', 'axcelersblocks' ) }
						help={ helpText }
						value={ width || height || '' }
						onChange={ handleLinkedChange }
						placeholder={ linkedPlaceholder }
						preset="iconSize"
					/>
				) : (
					<>
						<UnitValueControl
							label={ __( 'Width', 'axcelersblocks' ) }
							value={ width || '' }
							onChange={ handleWidthChange }
							placeholder={ widthPlaceholder }
							preset="iconSize"
						/>
						<UnitValueControl
							label={ __( 'Height', 'axcelersblocks' ) }
							value={ height || '' }
							onChange={ handleHeightChange }
							placeholder={ heightPlaceholder }
							preset="iconSize"
						/>
					</>
				) }
			</div>
		</PanelBody>
	);
}
