import { ColorPicker } from '@wordpress/components';
import { useState, useRef, useEffect } from '@wordpress/element';

const DefaultIcon = () => (
    <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
        <circle cx="13.5" cy="6.5" r="1.5" fill="currentColor" stroke="none"/>
        <circle cx="17.5" cy="10.5" r="1.5" fill="currentColor" stroke="none"/>
        <circle cx="8.5" cy="7.5" r="1.5" fill="currentColor" stroke="none"/>
        <circle cx="6.5" cy="12.5" r="1.5" fill="currentColor" stroke="none"/>
        <path d="M12 2C6.5 2 2 6.5 2 12s4.5 10 10 10c.9 0 1.5-.7 1.5-1.5 0-.4-.1-.7-.3-.9-.2-.2-.3-.5-.3-.8 0-.8.7-1.5 1.5-1.5H16c3.3 0 6-2.7 6-6 0-4.8-4.5-9-10-9z"/>
    </svg>
);

function Colorpicker({
    id = 'color',
    title = 'Color',
    text = 'Set the color of something.',
    defaultValue = '#000000',
    onChange = () => {},
    icon = <DefaultIcon />,
    hint = ''
}) {
    const [color, setColor] = useState(defaultValue || '#000000');
    const [open, setOpen] = useState(false);
    const popoverRef = useRef(null);
    const triggerRef = useRef(null);

    useEffect(() => {
        const onOutsideClick = (e) => {
            if (
                popoverRef.current && !popoverRef.current.contains(e.target) &&
                triggerRef.current && !triggerRef.current.contains(e.target)
            ) {
                setOpen(false);
            }
        };
        document.addEventListener('mousedown', onOutsideClick);
        return () => document.removeEventListener('mousedown', onOutsideClick);
    }, []);

    const handleColorChange = (newColor) => {
        const val = typeof newColor === 'string' ? newColor : (newColor?.hex || newColor?.color?.hex || '#000000');
        setColor(val);
        onChange({ target: { name: id, value: val } });
    };

    const displayHex = (color || '#000000').toUpperCase().replace(/^#?/, '#').slice(0, 7);

    return (
        <div className="strb-offcanvas-option-item strb-d-flex strb-align-items-center strb-justify-content-between strb-flex-wrap">
            {icon && <span className="strb-oc-ico">{icon}</span>}
            <div className="strb-offcanvas-option-content">
                <h4 className="strb-offcanvas-option-title">{title}</h4>
                <p>{text}</p>
            </div>
            <div className="strb-offcanvas-option-action">
                <div className="strb-color-wrap">
                    <button
                        ref={triggerRef}
                        type="button"
                        className={`strb-color-trigger${open ? ' is-open' : ''}`}
                        onClick={() => setOpen(o => !o)}
                        aria-label={`Pick color for ${title}`}
                    >
                        <span className="strb-color-dot" style={{ background: displayHex }} />
                        <span className="strb-color-hex">{displayHex}</span>
                        <svg className="strb-color-caret" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round">
                            <path d="m6 9 6 6 6-6"/>
                        </svg>
                    </button>
                    {open && (
                        <div ref={popoverRef} className="strb-color-popover">
                            <ColorPicker
                                color={color}
                                onChange={handleColorChange}
                                enableAlpha={false}
                                copyFormat="hex"
                            />
                        </div>
                    )}
                </div>
                {hint && <span className="strb-oc-hint">{hint}</span>}
            </div>
        </div>
    );
}

export default Colorpicker;
