import React, { useState, useEffect } from 'react';
import ConfirmModal from './ConfirmModal';

const IconPicker = ({ value, onChange, label, context = '' }) => {
    const [isOpen, setIsOpen] = useState(false);
    const [searchTerm, setSearchTerm] = useState('');
    const [iconLibrary, setIconLibrary] = useState({});
    const [customIcons, setCustomIcons] = useState([]);
    const [showAddIconModal, setShowAddIconModal] = useState(false);
    const [newIconClass, setNewIconClass] = useState('');
    const [newIconName, setNewIconName] = useState('');
    const [confirmModal, setConfirmModal] = useState({ isOpen: false, iconClass: '', iconName: '' });

    // Load FontAwesome icons and custom icons from backend
    useEffect(() => {
        if (window.proddispAdmin && window.proddispAdmin.fontAwesome && window.proddispAdmin.fontAwesome.icons) {
            setIconLibrary(window.proddispAdmin.fontAwesome.icons);
        }
        loadCustomIcons();
    }, []);

    // Load custom icons from database
    const loadCustomIcons = async () => {
        try {
            const response = await fetch(proddispAdmin.ajaxUrl, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/x-www-form-urlencoded',
                },
                body: new URLSearchParams({
                    action: 'proddisp_get_custom_icons',
                    nonce: proddispAdmin.nonce
                })
            });

            const data = await response.json();
            if (data.success) {
                setCustomIcons(data.data.icons || []);
            }
        } catch (error) {
            console.error('Error loading custom icons:', error);
        }
    };

    // Context-based icon suggestions
    const getContextualCategories = (context) => {
        const contextMap = {
            'cart': ['Shopping & E-commerce', 'Actions & Interactions'],
            'addtocart': ['Shopping & E-commerce', 'Actions & Interactions'],
            'wishlist': ['Actions & Interactions', 'User & People'],
            'compare': ['Actions & Interactions', 'Interface & Controls'],
            'quickview': ['Actions & Interactions', 'Media & Files'],
            'share': ['Communication & Social', 'Actions & Interactions'],
            'search': ['Interface & Controls', 'Actions & Interactions'],
            'filter': ['Interface & Controls', 'Actions & Interactions'],
            'user': ['User & People', 'Security & Safety'],
            'settings': ['Interface & Controls', 'Technology & Devices']
        };

        // Extract context from label or value if context not provided
        const contextKey = context.toLowerCase() ||
            label.toLowerCase() ||
            (value && value.includes('cart') ? 'cart' : '') ||
            (value && value.includes('heart') ? 'wishlist' : '') ||
            (value && value.includes('eye') ? 'quickview' : '') ||
            (value && value.includes('balance') ? 'compare' : '');

        // Find matching context
        for (const [key, categories] of Object.entries(contextMap)) {
            if (contextKey.includes(key)) {
                return categories;
            }
        }

        return [];
    };

    // Get prioritized categories based on context
    const getPrioritizedCategories = () => {
        const contextualCategories = getContextualCategories(context || label);
        const allCategories = Object.keys(iconLibrary);

        // Put contextual categories first, then the rest
        const prioritized = [...contextualCategories];
        allCategories.forEach(cat => {
            if (!prioritized.includes(cat)) {
                prioritized.push(cat);
            }
        });

        return prioritized;
    };

    const allIcons = Object.values(iconLibrary).reduce((acc, category) => {
        return { ...acc, ...category };
    }, {});

    const filteredIcons = searchTerm
        ? Object.entries(allIcons).filter(([iconClass, name]) =>
            name.toLowerCase().includes(searchTerm.toLowerCase()) ||
            iconClass.toLowerCase().includes(searchTerm.toLowerCase())
        )
        : Object.entries(allIcons);

    const handleIconSelect = (iconClass) => {
        onChange(iconClass);
        setIsOpen(false);
        setSearchTerm('');
    };

    // Add custom icon
    const handleAddCustomIcon = async () => {
        if (!newIconClass.trim() || !newIconName.trim()) {
            if (window.proddispToast) {
                window.proddispToast.error('Please enter both icon class and name');
            }
            return;
        }

        // Validate FontAwesome class format
        const iconClassPattern = /^(fas|far|fab|fal|fad|fat)\s+fa-[\w-]+$/;
        if (!iconClassPattern.test(newIconClass.trim())) {
            if (window.proddispToast) {
                window.proddispToast.error('Please enter a valid FontAwesome class (e.g., "fas fa-custom-icon")');
            }
            return;
        }

        try {
            const response = await fetch(proddispAdmin.ajaxUrl, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/x-www-form-urlencoded',
                },
                body: new URLSearchParams({
                    action: 'proddisp_add_custom_icon',
                    nonce: proddispAdmin.nonce,
                    icon_class: newIconClass.trim(),
                    icon_name: newIconName.trim()
                })
            });

            const data = await response.json();
            if (data.success) {
                // Reload custom icons
                await loadCustomIcons();

                // Clear form and close modal
                setNewIconClass('');
                setNewIconName('');
                setShowAddIconModal(false);

                // Show success message
                if (window.proddispToast) {
                    window.proddispToast.success('Custom icon added successfully!');
                }
            } else {
                if (window.proddispToast) {
                    window.proddispToast.error('Error adding custom icon: ' + (data.data?.message || 'Unknown error'));
                }
            }
        } catch (error) {
            console.error('Error adding custom icon:', error);
            if (window.proddispToast) {
                window.proddispToast.error('Error adding custom icon. Please try again.');
            }
        }
    };

    // Show remove confirmation modal
    const showRemoveConfirmation = (iconClass, iconName) => {
        setConfirmModal({
            isOpen: true,
            iconClass: iconClass,
            iconName: iconName
        });
    };

    // Remove custom icon
    const handleRemoveCustomIcon = async () => {
        const { iconClass } = confirmModal;

        try {
            const response = await fetch(proddispAdmin.ajaxUrl, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/x-www-form-urlencoded',
                },
                body: new URLSearchParams({
                    action: 'proddisp_remove_custom_icon',
                    nonce: proddispAdmin.nonce,
                    icon_class: iconClass
                })
            });

            const data = await response.json();
            if (data.success) {
                // Reload custom icons
                await loadCustomIcons();

                // Show success message
                if (window.proddispToast) {
                    window.proddispToast.success('Custom icon removed successfully!');
                }
            } else {
                if (window.proddispToast) {
                    window.proddispToast.error('Error removing custom icon: ' + (data.data?.message || 'Unknown error'));
                }
            }
        } catch (error) {
            console.error('Error removing custom icon:', error);
            if (window.proddispToast) {
                window.proddispToast.error('Error removing custom icon. Please try again.');
            }
        }
    };

    // Get popular icons for quick access
    const getPopularIcons = () => {
        const popular = {
            'fas fa-shopping-cart': 'Shopping Cart',
            'fas fa-heart': 'Heart',
            'far fa-heart': 'Heart Outline',
            'fas fa-eye': 'Eye',
            'fas fa-balance-scale': 'Balance Scale',
            'fas fa-star': 'Star',
            'fas fa-share': 'Share',
            'fas fa-search': 'Search',
            'fas fa-user': 'User',
            'fas fa-cog': 'Settings'
        };
        return Object.entries(popular);
    };

    return (
        <div className="icon-picker-container">
            <label className="icon-picker-label">{label}</label>

            <div className="icon-picker-trigger" onClick={() => setIsOpen(!isOpen)}>
                <div className="selected-icon">
                    {value ? (
                        <i className={`icon-display ${value}`}></i>
                    ) : (
                        <span className="icon-placeholder">Select Icon</span>
                    )}
                </div>
                <span className="dropdown-arrow">{isOpen ? '▲' : '▼'}</span>
            </div>

            {isOpen && (
                <div className="icon-picker-dropdown">
                    <div className="icon-search">
                        <input
                            type="text"
                            placeholder="Search icons..."
                            value={searchTerm}
                            onChange={(e) => setSearchTerm(e.target.value)}
                            className="icon-search-input"
                        />
                    </div>

                    <div className="icon-categories">
                        {/* Show popular icons first if no search */}
                        {!searchTerm && (
                            <div className="icon-category popular-icons">
                                <h4 className="category-title">
                                    <i className="fas fa-star"></i> Popular Icons
                                    <button
                                        className="add-custom-icon-btn"
                                        onClick={() => setShowAddIconModal(true)}
                                        title="Add Custom Icon"
                                    >
                                        <i className="fas fa-plus"></i>
                                    </button>
                                </h4>
                                <div className="icon-grid">
                                    {getPopularIcons().map(([iconClass, name]) => (
                                        <button
                                            key={iconClass}
                                            className={`icon-option ${value === iconClass ? 'selected' : ''}`}
                                            onClick={() => handleIconSelect(iconClass)}
                                            title={name}
                                        >
                                            <i className={iconClass}></i>
                                        </button>
                                    ))}
                                </div>
                            </div>
                        )}

                        {/* Show custom icons if any exist */}
                        {!searchTerm && customIcons.length > 0 && (
                            <div className="icon-category custom-icons">
                                <h4 className="category-title">
                                    <i className="fas fa-user-cog"></i> Custom Icons
                                </h4>
                                <div className="icon-grid">
                                    {customIcons.map((icon) => (
                                        <div key={icon.icon_class} className="custom-icon-wrapper">
                                            <button
                                                className={`icon-option ${value === icon.icon_class ? 'selected' : ''}`}
                                                onClick={() => handleIconSelect(icon.icon_class)}
                                                title={icon.icon_name}
                                            >
                                                <i className={icon.icon_class}></i>
                                            </button>
                                            <button
                                                className="remove-custom-icon"
                                                onClick={(e) => {
                                                    e.stopPropagation();
                                                    showRemoveConfirmation(icon.icon_class, icon.icon_name);
                                                }}
                                                title="Remove custom icon"
                                            >
                                                <i className="fas fa-times"></i>
                                            </button>
                                        </div>
                                    ))}
                                </div>
                            </div>
                        )}

                        {/* Show categories in prioritized order */}
                        {getPrioritizedCategories().map((categoryName) => {
                            const icons = iconLibrary[categoryName] || {};
                            const categoryIcons = Object.entries(icons).filter(([iconClass, name]) =>
                                !searchTerm ||
                                name.toLowerCase().includes(searchTerm.toLowerCase()) ||
                                iconClass.toLowerCase().includes(searchTerm.toLowerCase())
                            );

                            if (categoryIcons.length === 0) return null;

                            const contextualCategories = getContextualCategories(context || label);
                            const isContextual = contextualCategories.includes(categoryName);

                            return (
                                <div key={categoryName} className={`icon-category ${isContextual ? 'contextual-category' : ''}`}>
                                    <h4 className="category-title">
                                        {isContextual && <i className="fas fa-thumbtack"></i>} {categoryName}
                                        {isContextual && <span className="contextual-badge">Suggested</span>}
                                    </h4>
                                    <div className="icon-grid">
                                        {categoryIcons.map(([iconClass, name]) => (
                                            <button
                                                key={iconClass}
                                                className={`icon-option ${value === iconClass ? 'selected' : ''}`}
                                                onClick={() => handleIconSelect(iconClass)}
                                                title={name}
                                            >
                                                <i className={iconClass}></i>
                                            </button>
                                        ))}
                                    </div>
                                </div>
                            );
                        })}
                    </div>

                    {searchTerm && filteredIcons.length === 0 && (
                        <div className="no-icons-found">
                            <p>No icons found for "{searchTerm}"</p>
                            <small>Try searching for: cart, heart, eye, star, user, etc.</small>
                        </div>
                    )}

                    {Object.keys(iconLibrary).length === 0 && (
                        <div className="loading-icons">
                            <p>Loading icons...</p>
                        </div>
                    )}
                </div>
            )}

            {/* Add Custom Icon Modal */}
            {showAddIconModal && (
                <div className="custom-icon-modal-overlay" onClick={() => setShowAddIconModal(false)}>
                    <div className="custom-icon-modal" onClick={(e) => e.stopPropagation()}>
                        <div className="modal-header">
                            <h3>Add Custom Icon</h3>
                            <button
                                className="modal-close"
                                onClick={() => setShowAddIconModal(false)}
                            >
                                <i className="fas fa-times"></i>
                            </button>
                        </div>

                        <div className="modal-body">
                            <div className="form-group">
                                <label>FontAwesome Class</label>
                                <input
                                    type="text"
                                    value={newIconClass}
                                    onChange={(e) => setNewIconClass(e.target.value)}
                                    placeholder="e.g., fas fa-custom-icon"
                                    className="form-control"
                                />
                                <small className="form-help">
                                    Enter the complete FontAwesome class (e.g., "fas fa-rocket", "far fa-heart")
                                </small>
                            </div>

                            <div className="form-group">
                                <label>Icon Name</label>
                                <input
                                    type="text"
                                    value={newIconName}
                                    onChange={(e) => setNewIconName(e.target.value)}
                                    placeholder="e.g., Custom Rocket"
                                    className="form-control"
                                />
                                <small className="form-help">
                                    Enter a friendly name for this icon
                                </small>
                            </div>

                            {/* Preview */}
                            {newIconClass && (
                                <div className="icon-preview">
                                    <label>Preview:</label>
                                    <div className="preview-icon">
                                        <i className={newIconClass}></i>
                                        <span>{newIconName || 'Custom Icon'}</span>
                                    </div>
                                </div>
                            )}
                        </div>

                        <div className="modal-footer">
                            <button
                                className="button button-secondary"
                                onClick={() => setShowAddIconModal(false)}
                            >
                                Cancel
                            </button>
                            <button
                                className="button button-primary"
                                onClick={handleAddCustomIcon}
                                disabled={!newIconClass.trim() || !newIconName.trim()}
                            >
                                Add Icon
                            </button>
                        </div>
                    </div>
                </div>
            )}

            {/* Remove Icon Confirmation Modal */}
            <ConfirmModal
                isOpen={confirmModal.isOpen}
                onClose={() => setConfirmModal({ isOpen: false, iconClass: '', iconName: '' })}
                onConfirm={handleRemoveCustomIcon}
                title="Remove Custom Icon"
                message={`Are you sure you want to remove the custom icon "${confirmModal.iconName}"? This action cannot be undone.`}
                confirmText="Remove Icon"
                cancelText="Cancel"
                type="danger"
            />
        </div>
    );
};

export default IconPicker;