import { __ } from '@wordpress/i18n';
import { BaseControl, RangeControl, ToggleControl } from '@wordpress/components';
import { useState } from '@wordpress/element';
import { AllRadiusIcon, TopLeftIcon, TopRightIcon, BottomLeftIcon, BottomRightIcon } from '../components/constants/Icons';
import ResponsiveDeviceButtons from './ResponsiveDeviceButtons';
import { usePanelBodyClass } from '../components/PanelIndicator';
import { useIconPanelBodyClass } from '../components/IconPanelIndicator';

const ResponsiveRadiusControl = ( {
	attributes,
	setAttributes,
	attributeKeys,
	label,
	minValues = { desktop: 0, tablet: 0, mobile: 0 },
	maxValues = { desktop: 100, tablet: 100, mobile: 100 },
	defaultValue = 10,
	syncKey,
	ResetComponent,
	panelTitle,
	blockType
} ) => {
	const [ localDeviceType, setLocalDeviceType ] = useState( 'desktop' );
	const [ syncState, setSyncState ] = useState( attributes[ syncKey ] || false );

	// Dynamically choose the panel body class hook based on block type
	const panelBodyClass = blockType === 'smart-social-media-buttons/main'
		? usePanelBodyClass
		: useIconPanelBodyClass;

	// Use the custom hook to handle the panel class update
	panelBodyClass( attributes, Object.values( attributeKeys ), localDeviceType, panelTitle );

	const sides = [ 'topLeft', 'topRight', 'bottomLeft', 'bottomRight' ];
	const sideIcons = {
		topLeft: <TopLeftIcon />,
		topRight: <TopRightIcon />,
		bottomLeft: <BottomLeftIcon />,
		bottomRight: <BottomRightIcon />,
		all: <AllRadiusIcon />,
	};

	// Get the value for each side and device type
	const getValueForSide = ( side, deviceType ) => {
		const desktopValue = attributes[attributeKeys[ side ].desktop];
		const tabletValue = attributes[attributeKeys[ side ].tablet] || desktopValue;
		const mobileValue = attributes[attributeKeys[ side ].mobile] || tabletValue || desktopValue;

		return {
			desktop: desktopValue,
			tablet: tabletValue,
			mobile: mobileValue,
		}[ deviceType ];
	};

	// Handle value change
	const handleValueChange = ( newValue, side = null ) => {
		const newAttributes = { ...attributes };

		if ( syncState ) {
			// If sync is active, apply value to all sides
			sides.forEach( ( s ) => {
				newAttributes[ attributeKeys[ s ][ localDeviceType ] ] = newValue;
			} );
		} else if ( side ) {
			// Apply value to a specific side
			newAttributes[ attributeKeys[ side ][ localDeviceType ] ] = newValue;
		}
		setAttributes( newAttributes );
	};

	// Handle input change for valid integers
	const handleInputChange = ( e, side = null ) => {
		let inputValue = e.target.value;

		// Remove leading zeros while typing
		inputValue = inputValue.replace( /^0+(?!$)/, '' );

		// Parse to integer
		let newValue = parseInt( inputValue, 10 );
		if ( isNaN( newValue ) ) {
			newValue = 0;
		}

		// Allow values greater than max but restrict below min
		if ( newValue < minValues[localDeviceType] ) {
			newValue = minValues[localDeviceType];
		}

		// Update the input field with the corrected value
		e.target.value = newValue;
		handleValueChange( newValue, side );
	};

	// Handle reset for all or individual sides
	const resetValues = ( side = null ) => {
		const resetAttributes = {};

		if ( syncState ) {
			// Reset all sides if sync is enabled
			sides.forEach( ( s ) => {
				resetAttributes[ attributeKeys[ s ][ localDeviceType ] ] = defaultValue;
			} );
		} else if ( side ) {
			// Reset only one side if sync is disabled
			resetAttributes[ attributeKeys[ side ][ localDeviceType ] ] = defaultValue;
		}
		setAttributes( resetAttributes );
	};

	return (
		<BaseControl __nextHasNoMarginBottom = { true }>
			<div className="ssmb-control-header">
				<span className="ssmb-control-label">{ label }</span>
				<ResponsiveDeviceButtons localDeviceType = { localDeviceType } setLocalDeviceType = { setLocalDeviceType } />
			</div>

			{/* Sync Toggle */}
			<ToggleControl
				label = { __( 'Apply to all corners', 'smart-social-media-buttons' ) }
				checked = { syncState }
				onChange = { ( newSync ) => {
					setSyncState( newSync );
					setAttributes( { [ syncKey ]: newSync } );
				} }
				__nextHasNoMarginBottom = { true }
			/>

			{/* Radius Controls */}
			{syncState ? (
			// Single control for all corners
				<>
					<div className="ssmb-range-control">
						<RangeControl
							label = { sideIcons.all }
							value = { getValueForSide( sides[ 0 ], localDeviceType ) }
							onChange = { ( value ) => handleValueChange( value ) }
							min = { minValues[ localDeviceType ] }
							max = { maxValues[ localDeviceType ] }
							__nextHasNoMarginBottom = { true }
						/>
						{/* Separate Input for Manual Entry */}
						<input
							type = "number"
							value = { getValueForSide( sides[ 0 ], localDeviceType ) }
							onChange = { ( e ) => handleInputChange( e ) }
							min = { minValues[ localDeviceType ] }
							className = "ssmb-input-control"
							style = { { width: '64px', marginLeft: '15px', borderRadius: '2px' } }
						/>
						<ResetComponent
							currentAttributes = { attributes }
							attributeKeys = { sides.map( ( side ) => attributeKeys[ side ][ localDeviceType ] ) }
							setAttributes = { setAttributes }
							onClick = { () => resetValues() }
							defaultValue = { defaultValue }
							panelTitle = { panelTitle }
							blockType = { blockType }
						/>
					</div>
				</>
			) : (
			// Individual controls for each corner
				sides.map( ( side ) => (
					<div className="ssmb-range-control separated" key = { side }>
						<BaseControl label = { sideIcons[ side ] } __nextHasNoMarginBottom = { true }>
							<RangeControl
								value = { getValueForSide( side, localDeviceType ) || defaultValue }
								onChange = { ( value ) => handleValueChange( value, side ) }
								min = { minValues[ localDeviceType ] }
								max = { maxValues[ localDeviceType ] }
								__nextHasNoMarginBottom = { true }
							/>
							{/* Separate Input for Manual Entry */}
							<input
								type="number"
								value={ getValueForSide( side, localDeviceType ) || defaultValue }
								onChange={ ( e ) => handleInputChange( e, side ) }
								min={ minValues[ localDeviceType ] }
								className="ssmb-input-control"
								style={{ width: '64px', marginLeft: '15px', borderRadius: '2px' }}
							/>
							<ResetComponent
								currentAttributes = { attributes }
								attributeKeys = { [ attributeKeys[ side ][ localDeviceType ] ] }
								setAttributes = { setAttributes }
								onClick = { () => resetValues( side ) }
								defaultValue = { defaultValue }
								panelTitle = { panelTitle }
								blockType = { blockType }
							/>
						</BaseControl>
					</div>
				) )
			)}
		</BaseControl>
	);
};

export default ResponsiveRadiusControl;
