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

/**
 * Check if a value is an image URL (not an FA class)
 */
export const isImageValue = (val) => {
    if (!val) return false;
    return val.startsWith('http') || val.startsWith('//') || val.startsWith('/');
};

const ICON_SIZE = 18;

const IconPicker = ({ value, onChange, icons }) => {
    const [isOpen, setIsOpen] = useState(false);
    const [search, setSearch] = useState('');
    const [activeTab, setActiveTab] = useState(isImageValue(value) ? 'image' : 'icon');
    const containerRef = useRef(null);

    // Close on click outside
    useEffect(() => {
        const handleClickOutside = (event) => {
            if (containerRef.current && !containerRef.current.contains(event.target)) {
                setIsOpen(false);
            }
        };

        document.addEventListener('mousedown', handleClickOutside);
        return () => document.removeEventListener('mousedown', handleClickOutside);
    }, []);

    const iconList = icons || [];

    const filteredIcons = search
        ? iconList.filter(icon =>
            icon.name.toLowerCase().includes(search.toLowerCase()) ||
            (icon.keywords && icon.keywords.toLowerCase().includes(search.toLowerCase()))
        )
        : iconList;

    const selectedIcon = (value && !isImageValue(value))
        ? iconList.find(icon => icon.class === value)
        : null;

    const isImage = isImageValue(value);

    const openMediaUploader = (e) => {
        e.stopPropagation();

        if (typeof wp === 'undefined' || !wp.media) {
            return;
        }

        const frame = wp.media({
            title: __('Select Icon Image', 'wpuf-pro'),
            button: { text: __('Use as Icon', 'wpuf-pro') },
            multiple: false,
            library: { type: 'image' }
        });

        frame.on('select', () => {
            const attachment = frame.state().get('selection').first().toJSON();
            // Prefer thumbnail size for icon usage
            const url = (attachment.sizes && attachment.sizes.thumbnail)
                ? attachment.sizes.thumbnail.url
                : attachment.url;
            onChange(url);
            setIsOpen(false);
        });

        frame.open();
    };

    /**
     * Renders the current value preview (FA icon or image)
     */
    const renderPreview = (size, color) => {
        if (isImage) {
            return <img src={value} alt="" style={{ width: size, height: size, objectFit: 'contain', display: 'inline-block', verticalAlign: 'middle' }} />;
        }
        if (selectedIcon) {
            return <i className={selectedIcon.class} style={{ fontSize: `${size}px`, color }}></i>;
        }
        return null;
    };

    return (
        <div className="wpuf-relative" ref={containerRef}>
            {/* Trigger */}
            <div
                className="wpuf-flex wpuf-items-center wpuf-justify-between wpuf-cursor-pointer wpuf-border wpuf-border-gray-300 wpuf-rounded-[6px] wpuf-bg-white wpuf-px-[14px] wpuf-py-[10px]"
                onClick={() => setIsOpen(!isOpen)}
                style={{ minHeight: '42px' }}
            >
                <div className="wpuf-flex wpuf-items-center wpuf-gap-2">
                    {(selectedIcon || isImage) ? (
                        <>
                            {renderPreview(16, '#374151')}
                            <span className="wpuf-text-gray-700" style={{ fontSize: '14px' }}>
                                {isImage ? __('Custom image', 'wpuf-pro') : selectedIcon.name}
                            </span>
                        </>
                    ) : (
                        <span className="wpuf-text-gray-400" style={{ fontSize: '14px' }}>
                            {__('Select an icon or upload image', 'wpuf-pro')}
                        </span>
                    )}
                </div>
                <div className="wpuf-flex wpuf-items-center wpuf-gap-1">
                    {value && (
                        <button
                            type="button"
                            className="wpuf-text-gray-400 hover:wpuf-text-red-500 wpuf-p-1"
                            onClick={(e) => {
                                e.stopPropagation();
                                onChange('');
                            }}
                        >
                            <svg className="wpuf-w-4 wpuf-h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M6 18L18 6M6 6l12 12" />
                            </svg>
                        </button>
                    )}
                    <svg
                        className={`wpuf-w-4 wpuf-h-4 wpuf-text-gray-400 wpuf-transition-transform ${isOpen ? 'wpuf-rotate-180' : ''}`}
                        fill="none" stroke="currentColor" viewBox="0 0 24 24"
                    >
                        <path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M19 9l-7 7-7-7" />
                    </svg>
                </div>
            </div>

            {/* Dropdown */}
            {isOpen && (
                <div
                    className="wpuf-absolute wpuf-z-50 wpuf-mt-1 wpuf-bg-white wpuf-border wpuf-border-gray-200 wpuf-rounded-lg wpuf-shadow-lg"
                    style={{ width: '400px' }}
                >
                    {/* Tabs */}
                    <div className="wpuf-flex wpuf-border-b wpuf-border-gray-200">
                        <button
                            type="button"
                            className={`wpuf-flex-1 wpuf-py-2 wpuf-text-sm wpuf-font-medium wpuf-text-center wpuf-transition-colors ${
                                activeTab === 'icon'
                                    ? 'wpuf-text-emerald-600 wpuf-border-b-2 wpuf-border-emerald-600'
                                    : 'wpuf-text-gray-500 hover:wpuf-text-gray-700'
                            }`}
                            onClick={() => setActiveTab('icon')}
                        >
                            {__('Select Icon', 'wpuf-pro')}
                        </button>
                        <button
                            type="button"
                            className={`wpuf-flex-1 wpuf-py-2 wpuf-text-sm wpuf-font-medium wpuf-text-center wpuf-transition-colors ${
                                activeTab === 'image'
                                    ? 'wpuf-text-emerald-600 wpuf-border-b-2 wpuf-border-emerald-600'
                                    : 'wpuf-text-gray-500 hover:wpuf-text-gray-700'
                            }`}
                            onClick={() => setActiveTab('image')}
                        >
                            {__('Upload Image', 'wpuf-pro')}
                        </button>
                    </div>

                    {activeTab === 'icon' && (
                        <>
                            {/* Search */}
                            <div className="wpuf-p-3 wpuf-border-b wpuf-border-gray-200">
                                <input
                                    type="text"
                                    className="wpuf-w-full !wpuf-m-0 !wpuf-leading-none !wpuf-py-[8px] !wpuf-px-[12px] wpuf-text-gray-700 !wpuf-shadow-sm placeholder:wpuf-text-gray-400 wpuf-border !wpuf-border-gray-300 !wpuf-rounded-[6px] focus:!wpuf-ring-transparent"
                                    placeholder={__('Search icons...', 'wpuf-pro')}
                                    value={search}
                                    onChange={(e) => setSearch(e.target.value)}
                                    autoFocus
                                />
                                <div className="wpuf-text-xs wpuf-text-gray-400 wpuf-mt-1">
                                    {filteredIcons.length} {__('icons found', 'wpuf-pro')}
                                </div>
                            </div>

                            {/* Icon Grid */}
                            <div
                                className="wpuf-p-3 wpuf-overflow-y-auto"
                                style={{ maxHeight: '300px' }}
                            >
                                {filteredIcons.length === 0 ? (
                                    <div className="wpuf-text-center wpuf-text-gray-400 wpuf-py-6" style={{ fontSize: '14px' }}>
                                        {__('No icons found', 'wpuf-pro')}
                                    </div>
                                ) : (
                                    <div className="wpuf-grid wpuf-grid-cols-4 wpuf-gap-1">
                                        {filteredIcons.map((icon) => (
                                            <button
                                                key={icon.class}
                                                type="button"
                                                className={`wpuf-flex wpuf-flex-col wpuf-items-center wpuf-justify-center wpuf-p-2 wpuf-rounded wpuf-cursor-pointer wpuf-transition-colors wpuf-border ${
                                                    value === icon.class
                                                        ? 'wpuf-bg-emerald-50 wpuf-border-emerald-300'
                                                        : 'wpuf-border-transparent hover:wpuf-bg-gray-100'
                                                }`}
                                                style={{ minHeight: '60px' }}
                                                onClick={() => {
                                                    onChange(icon.class);
                                                    setIsOpen(false);
                                                    setSearch('');
                                                }}
                                                title={icon.name}
                                            >
                                                <i className={icon.class} style={{ fontSize: `${ICON_SIZE}px`, color: '#374151' }}></i>
                                                <span className="wpuf-text-xs wpuf-text-gray-500 wpuf-mt-1 wpuf-truncate wpuf-w-full wpuf-text-center">
                                                    {icon.name}
                                                </span>
                                            </button>
                                        ))}
                                    </div>
                                )}
                            </div>
                        </>
                    )}

                    {activeTab === 'image' && (
                        <div className="wpuf-p-4">
                            {isImage ? (
                                <div className="wpuf-flex wpuf-flex-col wpuf-items-center wpuf-gap-3">
                                    <div className="wpuf-border wpuf-border-gray-200 wpuf-rounded wpuf-p-3 wpuf-bg-gray-50">
                                        <img
                                            src={value}
                                            alt=""
                                            style={{ width: '48px', height: '48px', objectFit: 'contain' }}
                                        />
                                    </div>
                                    <div className="wpuf-flex wpuf-gap-2">
                                        <button
                                            type="button"
                                            className="wpuf-text-sm wpuf-text-emerald-600 hover:wpuf-text-emerald-700 wpuf-font-medium"
                                            onClick={openMediaUploader}
                                        >
                                            {__('Replace', 'wpuf-pro')}
                                        </button>
                                        <button
                                            type="button"
                                            className="wpuf-text-sm wpuf-text-red-500 hover:wpuf-text-red-600 wpuf-font-medium"
                                            onClick={(e) => {
                                                e.stopPropagation();
                                                onChange('');
                                            }}
                                        >
                                            {__('Remove', 'wpuf-pro')}
                                        </button>
                                    </div>
                                </div>
                            ) : (
                                <div className="wpuf-flex wpuf-flex-col wpuf-items-center wpuf-gap-3 wpuf-py-4">
                                    <svg className="wpuf-w-10 wpuf-h-10 wpuf-text-gray-300" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                        <path strokeLinecap="round" strokeLinejoin="round" strokeWidth="1.5" d="M4 16l4.586-4.586a2 2 0 012.828 0L16 16m-2-2l1.586-1.586a2 2 0 012.828 0L20 14m-6-6h.01M6 20h12a2 2 0 002-2V6a2 2 0 00-2-2H6a2 2 0 00-2 2v12a2 2 0 002 2z" />
                                    </svg>
                                    <p className="wpuf-text-sm wpuf-text-gray-500">
                                        {__('Upload an image to use as icon', 'wpuf-pro')}
                                    </p>
                                    <button
                                        type="button"
                                        className="wpuf-text-sm wpuf-font-medium wpuf-text-white wpuf-rounded-md wpuf-px-4 wpuf-py-2 wpuf-transition-colors"
                                        style={{ backgroundColor: '#059669' }}
                                        onClick={openMediaUploader}
                                    >
                                        {__('Upload Image', 'wpuf-pro')}
                                    </button>
                                </div>
                            )}
                        </div>
                    )}
                </div>
            )}
        </div>
    );
};

export default IconPicker;
