import { useState, useRef, useEffect } from '@wordpress/element';
import { __ } from '@wordpress/i18n';

/**
 * CustomSelect Component
 * 
 * A premium, highly customizable select dropdown that replaces native <select>.
 * Supports groups, custom labels, and a premium "WhatsApp-style" dropdown UI.
 */
export default function CustomSelect({ options, value, onChange, placeholder, className = '', style = {} }) {
    const [isOpen, setIsOpen] = useState(false);
    const wrapperRef = useRef(null);

    // Close when clicking outside
    useEffect(() => {
        function handleClickOutside(event) {
            if (wrapperRef.current && !wrapperRef.current.contains(event.target)) {
                setIsOpen(false);
            }
        }
        document.addEventListener('mousedown', handleClickOutside);
        return () => document.removeEventListener('mousedown', handleClickOutside);
    }, []);

    // Get current label
    const selectedOption = options.find(o => o.value === value);
    const displayLabel = selectedOption ? selectedOption.label : (placeholder || __('Select...', 'shois-chat-button'));

    // Group options if needed (handles optgroup-like structure)
    const groups = {};
    const ungrouped = [];
    options.forEach(opt => {
        if (opt.group) {
            if (!groups[opt.group]) groups[opt.group] = [];
            groups[opt.group].push(opt);
        } else {
            ungrouped.push(opt);
        }
    });

    const toggleDropdown = (e) => {
        e.preventDefault();
        e.stopPropagation();
        setIsOpen(!isOpen);
    };

    const handleSelect = (e, val) => {
        e.preventDefault();
        e.stopPropagation();
        onChange(val);
        setIsOpen(false);
    };

    const renderOption = (opt) => (
        <div
            key={opt.value}
            className={`shcb-custom-select-option ${value === opt.value ? 'active' : ''}`}
            onClick={(e) => handleSelect(e, opt.value)}
        >
            <span className="shcb-option-label">{opt.label}</span>
            {value === opt.value && (
                <svg className="shcb-option-check" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="3" strokeLinecap="round" strokeLinejoin="round">
                    <polyline points="20 6 9 17 4 12"></polyline>
                </svg>
            )}
        </div>
    );

    return (
        <div 
            className={`shcb-custom-select-wrapper ${className} ${isOpen ? 'is-open' : ''}`} 
            ref={wrapperRef}
            style={{ ...style, position: 'relative' }}
        >
            <button 
                type="button"
                className="shcb-custom-select-trigger shcb-input" 
                onClick={toggleDropdown}
                aria-haspopup="listbox"
                aria-expanded={isOpen}
                style={{ textAlign: 'left', display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}
            >
                <span className="shcb-trigger-text">{displayLabel}</span>
                <span className="shcb-trigger-arrow">
                    <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round">
                        <polyline points="6 9 12 15 18 9"></polyline>
                    </svg>
                </span>
            </button>

            {isOpen && (
                <div className="shcb-custom-select-dropdown" style={{ zIndex: 999999 }}>
                    {ungrouped.map(renderOption)}
                    
                    {Object.entries(groups).map(([groupName, groupOptions]) => (
                        <div key={groupName} className="shcb-custom-select-group">
                            <div className="shcb-group-label">{groupName}</div>
                            {groupOptions.map(renderOption)}
                        </div>
                    ))}
                </div>
            )}
        </div>
    );
}
