import { __ } from '@wordpress/i18n';
import { BaseControl, RangeControl, ToggleControl } from '@wordpress/components';
import { useState } from '@wordpress/element';
import { SidesAllIcon, SideTopIcon, SideLeftIcon, SideRightIcon, SideBottomIcon } from '../components/constants/Icons';
import ResponsiveDeviceButtons from './ResponsiveDeviceButtons';
import { usePanelBodyClass } from '../components/PanelIndicator';
import { useIconPanelBodyClass } from '../components/IconPanelIndicator';

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

	// 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 = [ 'top', 'right', 'bottom', 'left' ];
	const sideIcons = {
		top: <SideTopIcon />,
		right: <SideRightIcon />,
		bottom: <SideBottomIcon />,
		left: <SideLeftIcon />,
		all: <SidesAllIcon />,
	};

	// Handle value changes for synced or individual sides
	const handleValueChange = ( newValue, side = null ) => {
		const newAttributes = { ...attributes };

		if ( syncState ) {
			// Apply value to all sides when sync is enabled
			sides.forEach( ( s ) => {
				newAttributes[ attributeKeys[ s ][ localDeviceType ] ] = newValue ?? 0; // Allow 0 to be set
			} );
		} else if ( side !== null ) {
			// Apply value to the specific side when sync is disabled
			newAttributes[ attributeKeys[ side ][ localDeviceType ] ] = newValue ?? 0; // Allow 0 to be set
		}

		setAttributes( newAttributes );
	};

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

		// Remove leading zeros and preserve single "0"
		inputValue = inputValue.replace( /^(-?)0+(?!$)/, '$1' );

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

		// Restrict negative input if min value is non-negative
		if ( minValues[localDeviceType] >= 0 && newValue < 0 ) {
			newValue = 0; // Reset to 0 if negative input is not allowed
		}

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

	// Reset specific or all values to the default
	const resetValues = ( side = null ) => {
		const resetAttributes = {};

		if ( syncState ) {
			// Reset all sides to default when sync is enabled
			sides.forEach( ( s ) => {
				resetAttributes[ attributeKeys[ s ][ localDeviceType ] ] = defaultValue;
			} );
		} else if ( side !== null ) {
			// Reset the specific side to default when sync is disabled
			resetAttributes[ attributeKeys[ side ][ localDeviceType ] ] = defaultValue;
		}

		setAttributes( resetAttributes );
	};

	// Get the values for each side for the desktop, tablet, and mobile devices
	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 ] ?? defaultValue; // Ensure 0 is allowed
	};

	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
				labe = { __( 'Apply to all sides', 'smart-social-media-buttons' ) }
				checked = { syncState }
				onChange = { ( newSync ) => {
					setSyncState( newSync );
					setAttributes( { [ syncKey ]: newSync } );
				} }
				__nextHasNoMarginBottom = { true }
			/>

			{/* Range control and reset button for all sides when sync is enabled */}
			{syncState ? (
				<>
					<div className="ssmb-range-control">
						<RangeControl
							label = { sideIcons.all }
							value = { getValueForSide( sides[ 0 ], localDeviceType ) ?? defaultValue }
							onChange = { ( value ) => handleValueChange( value ) }
							min = { minValues[ localDeviceType ] }
							max = { maxValues[ localDeviceType ] }
							__nextHasNoMarginBottom = { true }
						/>
						{/* Input for manual entry */}
						<input
							type="number"
							value = { getValueForSide( sides[ 0 ], localDeviceType ) ?? defaultValue }
							onChange = { ( e ) => handleInputChange( e ) }
							min = { minValues[ localDeviceType ] < 0 ? undefined : minValues[ localDeviceType ] } // Unrestricted when negative
							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() } // Reset all sides
							label = { __( 'Reset All', 'smart-social-media-buttons' ) }
							defaultValue = { defaultValue }
							panelTitle = { panelTitle }
							blockType = { blockType }
						/>
					</div>
				</>
			) : (
			// Individual controls for each side when sync is disabled
				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 }
							/>
							{/* Input for manual entry */}
							<input
								type="number"
								value = { getValueForSide( side, localDeviceType ) ?? defaultValue }
								onChange = { ( e ) => handleInputChange( e, side ) }
								min = { minValues[ localDeviceType ] < 0 ? undefined : minValues[ localDeviceType ] } // Unrestricted when negative
								className="ssmb-input-control"
								style = { { width: '64px', marginLeft: '15px', borderRadius: '2px' } }
							/>
							<ResetComponent
								currentAttributes = { attributes }
								attributeKeys = { [ attributeKeys[ side ][ localDeviceType ] ] }
								setAttributes = { setAttributes }
								onClick = { () => resetValues( side ) } // Reset individual side
								label = { __( 'Reset', 'smart-social-media-buttons' ) }
								defaultValue = { defaultValue }
								panelTitle = { panelTitle }
								blockType = { blockType }
							/>
						</BaseControl>
					</div>
				) )
			)}
		</BaseControl>
	);
};

export default ResponsiveSyncControl;
