/**
 * Font Awesome Icon Selector Component
 * 
 * A reusable component for selecting Font Awesome icons in block settings.
 */

import { useState, useEffect } from '@wordpress/element';
import { BaseControl, Button, Popover, TextControl, ToggleControl } from '@wordpress/components';
import { __ } from '@wordpress/i18n';

// Free Font Awesome icon categories and icons
const ICON_CATEGORIES = [
    { name: 'solid', label: __('Solid', 'zenblocks'), prefix: 'fas' },
    { name: 'regular', label: __('Regular', 'zenblocks'), prefix: 'far' },
    { name: 'brands', label: __('Brands', 'zenblocks'), prefix: 'fab' },
];

// Popular Font Awesome free icons by category
// This is a subset of free icons that can be extended as needed
const ICONS = {
    solid: [
        'fa-home', 'fa-user', 'fa-cog', 'fa-star', 'fa-heart', 'fa-check', 
        'fa-times', 'fa-plus', 'fa-minus', 'fa-search', 'fa-envelope',
        'fa-phone', 'fa-map-marker-alt', 'fa-calendar', 'fa-clock',
        'fa-arrow-right', 'fa-arrow-left', 'fa-arrow-up', 'fa-arrow-down'
    ],
    regular: [
        'fa-heart', 'fa-star', 'fa-user', 'fa-clock', 'fa-calendar',
        'fa-envelope', 'fa-comment', 'fa-file', 'fa-folder', 'fa-image'
    ],
    brands: [
        'fa-facebook', 'fa-twitter', 'fa-instagram', 'fa-linkedin',
        'fa-youtube', 'fa-github', 'fa-wordpress', 'fa-google'
    ]
};

/**
 * Font Awesome Icon Setting Component
 * 
 * @param {Object} props - Component properties
 * @param {string} props.label - Setting label
 * @param {string} props.value - Current icon value (e.g. 'fas fa-home')
 * @param {Function} props.onChange - onChange handler
 * @param {string} props.help - Optional help text
 * @returns {JSX.Element} Icon selector component
 */
const FontAwesomeIconSetting = ({ label, value = '', onChange, help }) => {
    const [isPickerOpen, setIsPickerOpen] = useState(false);
    const [searchTerm, setSearchTerm] = useState('');
    const [currentCategory, setCurrentCategory] = useState('solid');
    const [hasIcon, setHasIcon] = useState(!!value);

    // Parse current icon value
    const getIconDetails = () => {
        if (!value) return { prefix: 'fas', icon: '' };
        
        const parts = value.split(' ');
        return {
            prefix: parts[0] || 'fas',
            icon: parts.length > 1 ? parts[1] : ''
        };
    };

    const { prefix, icon } = getIconDetails();

    // Handle icon selection
    const selectIcon = (newPrefix, newIcon) => {
        onChange(`${newPrefix} ${newIcon}`);
        setIsPickerOpen(false);
    };

    // Handle icon toggle
    const toggleIcon = (isEnabled) => {
        setHasIcon(isEnabled);
        if (!isEnabled) {
            onChange('');
        } else if (!value) {
            onChange('fas fa-star'); // Default icon
        }
    };

    // Filter icons based on search term
    const getFilteredIcons = () => {
        if (!searchTerm) return ICONS[currentCategory];
        
        return ICONS[currentCategory].filter(icon => 
            icon.replace('fa-', '').includes(searchTerm.toLowerCase())
        );
    };

    // Get prefix display name
    const getPrefixLabel = (prefixCode) => {
        const category = ICON_CATEGORIES.find(cat => cat.prefix === prefixCode);
        return category ? category.label : prefixCode;
    };

    return (
        <BaseControl 
            label={label}
            help={help}
            className="zenblocks-icon-setting"
        >
            <div className="zenblocks-icon-control">
                <ToggleControl
                    label={__('Use Icon', 'zenblocks')}
                    checked={hasIcon}
                    onChange={toggleIcon}
                />
                
                {hasIcon && (
                    <div className="zenblocks-icon-preview">
                        <Button 
                            isSecondary
                            onClick={() => setIsPickerOpen(true)}
                            className="zenblocks-icon-button"
                        >
                            {value ? (
                                <>
                                    <i className={value}></i>
                                    <span className="zenblocks-icon-label">
                                        {`${getPrefixLabel(prefix)}: ${icon.replace('fa-', '')}`}
                                    </span>
                                </>
                            ) : __('Select Icon', 'zenblocks')}
                        </Button>
                        
                        {isPickerOpen && (
                            <Popover
                                className="zenblocks-icon-popover"
                                onClose={() => setIsPickerOpen(false)}
                            >
                                <div className="zenblocks-icon-picker">
                                    <div className="zenblocks-icon-picker-header">
                                        <TextControl
                                            placeholder={__('Search icons...', 'zenblocks')}
                                            value={searchTerm}
                                            onChange={setSearchTerm}
                                        />
                                        
                                        <div className="zenblocks-icon-category-tabs">
                                            {ICON_CATEGORIES.map((category) => (
                                                <Button
                                                    key={category.name}
                                                    isSmall
                                                    isPrimary={currentCategory === category.name}
                                                    isSecondary={currentCategory !== category.name}
                                                    onClick={() => setCurrentCategory(category.name)}
                                                >
                                                    {category.label}
                                                </Button>
                                            ))}
                                        </div>
                                    </div>
                                    
                                    <div className="zenblocks-icon-grid">
                                        {getFilteredIcons().map((iconName) => {
                                            const currentPrefix = ICON_CATEGORIES.find(
                                                c => c.name === currentCategory
                                            ).prefix;
                                            const iconClass = `${currentPrefix} ${iconName}`;
                                            
                                            return (
                                                <Button
                                                    key={iconName}
                                                    className="zenblocks-icon-item"
                                                    isSelected={value === iconClass}
                                                    onClick={() => selectIcon(currentPrefix, iconName)}
                                                >
                                                    <i className={iconClass}></i>
                                                    <span className="zenblocks-icon-name">
                                                        {iconName.replace('fa-', '')}
                                                    </span>
                                                </Button>
                                            );
                                        })}
                                    </div>
                                </div>
                            </Popover>
                        )}
                    </div>
                )}
            </div>
        </BaseControl>
    );
};

export default FontAwesomeIconSetting;
