import { useState, useRef, cloneElement, useEffect, useContext } from '@wordpress/element';
import { Button, Dashicon } from '@wordpress/components';
import { __ } from '@wordpress/i18n';
import { useSelect } from '@wordpress/data';
import { store as editorStore } from '@wordpress/editor';

import { useDevice  } from './deviceContext';

const DEVICES = [
	{ slug: 'desktop', label: __('Desktop', 'lead-gen'), icon: 'desktop' },
	{ slug: 'laptop', label: __('Laptop', 'lead-gen'), icon: 'laptop' },
	{ slug: 'large-tablet', label: __('Large Tablet', 'lead-gen'), icon: 'tablet' },
	{ slug: 'tablet', label: __('Tablet', 'lead-gen'), icon: 'tablet' },
	{ slug: 'mobile', label: __('Mobile', 'lead-gen'), icon: 'smartphone' },
];

const WP_DEVICE_MAP = {
	desktop: 'Desktop',
	laptop: 'Tablet', // Use Tablet as fallback for syncing preview toolbar
	'large-tablet': 'Tablet', // Use Tablet as fallback for syncing preview toolbar
	tablet: 'Tablet',
	mobile: 'Mobile',
};

const DeviceControl = ({ label, value, onChange, children }) => {
	const [activeDevice, setActiveDevice] = useDevice();
	const [isDropdownOpen, setDropdownOpen] = useState(false);
	const dropdownRef = useRef(null);

	const wpDevice = useSelect((select) => select(editorStore).getDeviceType(), []);
	useEffect(() => {
		if (wpDevice && wpDevice !== WP_DEVICE_MAP[activeDevice]) {
			const match = Object.entries(WP_DEVICE_MAP).find(([, wpVal]) => wpVal === wpDevice);
			if (match) setActiveDevice(match[0]); // map WP device back to your slug
		}
	}, [wpDevice]);


	const validDevice = DEVICES.some((d) => d.slug === activeDevice) ? activeDevice : 'desktop';
	const activeDeviceData = DEVICES.find((d) => d.slug === validDevice);
	const currentVal = value?.[validDevice] || '';

	const handleChange = (newVal) => {
		const updated = { ...value, [validDevice]: newVal };
		onChange(updated);
	};

	const setDeviceTypeSmart = (device) => {
		const wpDevice = WP_DEVICE_MAP[device] || 'Desktop';
	
		// Sync WordPress editor preview
		wp?.data?.dispatch('core/editor')?.setDeviceType?.(wpDevice);
		wp?.data?.dispatch('core/edit-post')?.__experimentalSetPreviewDeviceType?.(wpDevice);
	
		// Custom handling for laptop viewport simulation
		const iframe = document.querySelector('iframe[name="editor-canvas"]');
		if (iframe) {
			switch (device) {
				case 'mobile':
					iframe.style.width = '360px';
					break;
				case 'tablet':
					iframe.style.width = '640px';
					break;
				case 'large-tablet':
					iframe.style.width = '992px';
					break;
				case 'laptop':
					iframe.style.width = '1216px';
					break;
				case 'desktop':
					iframe.style.width = '100%';
					break;
				default:
					// Let WordPress handle width for 'tablet' and 'mobile'
					iframe.style.removeProperty('width');
					break;
			}
		}
	};

	const handleDeviceChange = (device) => {
		setActiveDevice(device);
		setDeviceTypeSmart(device);
		setDropdownOpen(false);
	};

	return (
		<div className="lg-device-control">
			{label ? <div className="lg-device-control__label">
				<strong>{label}</strong>
			</div> : null}

			<div className="lg-device-control__switcher-wrapper" ref={dropdownRef}>
				<Button
					className="lg-device-control__toggle"
					onClick={() => setDropdownOpen((open) => !open)}
					icon={<Dashicon icon={activeDeviceData?.icon || 'desktop'} />}
					label={activeDeviceData?.label || 'Desktop'}
					size="small"
				/>

				{isDropdownOpen && (
					<div className="lg-device-control__dropdown">
						{DEVICES.map((device) => {
							const isActive = device.slug === validDevice;
							return (
								<Button
									key={device.slug}
									size="small"
									className={`lg-device-control__device-button${isActive ? ' is-active' : ''}`}
									onClick={() => handleDeviceChange(device.slug)}
									icon={<Dashicon icon={device.icon} />}
									label={device.label}
								/>
							);
						})}
					</div>
				)}
			</div>

			{cloneElement(children, {
				value: currentVal,
				onChange: handleChange,
				className: 'lg-device-control__input',
			})}
		</div>
	);
};

export default DeviceControl;
