import {
	Button,
	BaseControl,
	ColorPalette,
	RangeControl,
	PanelBody,
} from '@wordpress/components';
import { __ } from '@wordpress/i18n';
import { useEffect, useRef, useState } from '@wordpress/element';
import { useSelect } from '@wordpress/data';
import { store as blockEditorStore } from '@wordpress/block-editor';

import { loadMaterialSymbolsFont, isFontLoaded } from '../../utils/fontLoader';

const arrowIcons = [
	{ label: __('None', 'your-text-domain'), value: '', next: '', prev: '' },
	{
		label: __('Arrow', 'your-text-domain'),
		value: 'arrow',
		next: 'arrow_forward',
		prev: 'arrow_back',
	},
	{
		label: __('Chevron', 'your-text-domain'),
		value: 'chevron',
		next: 'chevron_right',
		prev: 'chevron_left',
	},

	{
		label: __('Double Arrow', 'your-text-domain'),
		value: 'double_arrow',
		next: 'keyboard_double_arrow_right',
		prev: 'keyboard_double_arrow_left',
	},
];

const IconSelector = ({ value, onChange, iconStyle, onIconStyleChange }) => {
	const [fontReady, setFontReady] = useState(isFontLoaded());
	const styleElementRef = useRef(null);

	useEffect(() => {
		if (!fontReady) {
			loadMaterialSymbolsFont().then(() => {
				setFontReady(true);
			});
		}
	}, []);

	useEffect(() => {
		if (fontReady) {
			const timer = setTimeout(() => {
				updateStyles();
			}, 0);
			return () => clearTimeout(timer);
		}
	}, [fontReady, iconStyle]);

	const updateStyles = () => {
		if (!styleElementRef.current) {
			styleElementRef.current = document.createElement('style');
			document.head.appendChild(styleElementRef.current);
		}

		styleElementRef.current.textContent = `
      .icon-selector-grid {
        display: grid;
        grid-template-columns: repeat(auto-fill, minmax(40px, 1fr));
        gap: 8px;
        margin-top: 8px;
      }

      .icon-selector-button.components-button {
        display: flex !important;
        justify-content: center !important;
        align-items: center !important;
        padding: 8px !important;
        height: 40px !important;
        width: 40px !important;
        min-width: 40px !important;
      }

      .icon-selector-button .material-symbols-outlined,
      .icon-selector-button .material-icons {
        font-size: ${iconStyle.size}px;
        font-variation-settings:
          'FILL' ${iconStyle.fill},
          'wght' ${iconStyle.weight},
          'GRAD' 0,
          'opsz' 48;
        color: #000000;
      }

      .icon-selector-button.is-primary {
        background-color: #2669e6;
        color: white;
      }
    `;
	};

	const colors = useSelect((select) => {
		const settings = select(blockEditorStore).getSettings();
		return settings.colors || [];
	}, []);

	return fontReady ? (
		<PanelBody title="Icon Settings" initialOpen={false}>
			<BaseControl label={__('Type', 'your-text-domain')}>
				<div className="icon-selector-grid">
					{arrowIcons.map((icon) => (
						<Button
							key={icon.value}
							isSecondary
							isPrimary={value === icon.value}
							onClick={() =>
								onChange({
									next: icon.next,
									prev: icon.prev,
								})
							}
							aria-label={icon.label}
							className="icon-selector-button"
						>
							<span className="material-symbols-outlined">
								{icon.next}
							</span>
						</Button>
					))}
				</div>
			</BaseControl>
			<RangeControl
				label={__('Weight', 'your-text-domain')}
				value={iconStyle.weight}
				onChange={(weight) => onIconStyleChange({ weight })}
				min={100}
				max={700}
				step={100}
			/>
			<RangeControl
				label={__('Size', 'your-text-domain')}
				value={iconStyle.size}
				onChange={(size) => onIconStyleChange({ size })}
				min={16}
				max={100}
				step={1}
			/>
			<ColorPalette
				colors={colors}
				label={__('Color', 'your-text-domain')}
				value={iconStyle.color}
				onChange={(color) => onIconStyleChange({ color })}
			/>
		</PanelBody>
	) : (
		<div>Loading font...</div>
	);
};

export default IconSelector;
