import { Button } from '@wordpress/components';
import { useSelect, useDispatch } from '@wordpress/data';
import { useState, useEffect } from '@wordpress/element';
import { DesktopIcon, TabletIcon, MobileIcon } from '../components/constants/Icons';

const ResponsiveDeviceButtons = ( { localDeviceType, setLocalDeviceType } ) => {
	const hasEditorStore = useSelect( () => !!wp.data.select( 'core/editor' ), [] );
	const { setDeviceType } = hasEditorStore ? useDispatch( 'core/editor' ) : { setDeviceType: null };
	const currentDeviceType = hasEditorStore ? useSelect( ( select ) => select( 'core/editor' ).getDeviceType(), [] ) : null;

	const [ isOpen, setIsOpen ] = useState( false );

	useEffect( () => {
		if ( currentDeviceType ) {
			setLocalDeviceType( currentDeviceType.toLowerCase() );
		}
	}, [ currentDeviceType ] );

	const handleDeviceTypeChange = ( newDeviceType ) => {
		if ( setDeviceType ) {
			setDeviceType( newDeviceType );
		}
		setLocalDeviceType( newDeviceType.toLowerCase() );
		setIsOpen( false ); // Close dropdown on selection
	};

	const toggleDropdown = () => {
		setIsOpen( !isOpen );
	};

	return (
		<div className={ `ssmb-toggle-buttons-container ${isOpen ? 'is-open' : ''}`} >
			<Button
				icon = { localDeviceType === 'desktop' ? <DesktopIcon /> : localDeviceType === 'tablet' ? <TabletIcon /> : <MobileIcon /> }
				aria-expanded = { isOpen }
				aria-label = { 'Toggle device selection' }
				onClick = { toggleDropdown }
				className={ `ssmb-toggle-buttons-toggle ${isOpen ? 'is-open' : ''}` }
			/>
			{isOpen && (
				<div className="ssmb-toggle-buttons-stack">
					<Button
						icon = { <DesktopIcon /> }
						label = { 'Desktop' }
						onClick = { () => handleDeviceTypeChange( 'Desktop' ) }
						className={ localDeviceType === 'desktop' ? 'is-selected' : '' }
					/>
					<Button
						icon = { <TabletIcon /> }
						label = { 'Tablet' }
						onClick = { () => handleDeviceTypeChange( 'Tablet' ) }
						className={ localDeviceType === 'tablet' ? 'is-selected' : '' }
					/>
					<Button
						icon = { <MobileIcon /> }
						label = { 'Mobile' }
						onClick = { () => handleDeviceTypeChange( 'Mobile' ) }
						className={ localDeviceType === 'mobile' ? 'is-selected' : '' }
					/>
				</div>
			)}
		</div>
	);
};

export default ResponsiveDeviceButtons;
