import { useState, useEffect } from 'react';
import { __ } from '@wordpress/i18n';
import { SelectControl } from '@wordpress/components';

export function IconSelectControl(props) {
    const { iconSvgId, onIconChange } = props;

    const [iconData, setIconData] = useState([]);

    useEffect(() => {
        const fetchIconData = async () => {
            try {
                const response = await fetch('/wp-json/lcp/v1/icons');
                const data = await response.json();
                if (Array.isArray(data) && data.length > 0) {
                    setIconData(data);  // Set the fetched data directly
                }
            } catch (error) {
                console.error('Error fetching icons:', error);
            }
        };

        fetchIconData();
    }, []);

    const handleIconChange = (selectedIconId) => {
        const selectedIcon = iconData.find(icon => icon.iconSvgId === selectedIconId);
        if (selectedIcon && onIconChange) {
            // Send both icon ID and path (SVG) to the parent component
            onIconChange({
                iconSvgId: selectedIcon.iconSvgId,   // Pass icon ID to parent
                iconSvgPath: selectedIcon.iconSvgPaths,  // Pass icon paths to parent
                viewbox: selectedIcon.selectedIconViewbox // Pass the viewbox to parent
            });
            console.log("Selected Icon ID:", selectedIcon.iconSvgId);  // Debugging output
            console.log("Selected Icon Path:", selectedIcon.iconSvgPaths);  // Debugging output
            console.log("Selected Icon Viewbox:", selectedIcon.selectedIconViewbox); // Debugging output
        }
    };

    if (iconData.length === 0) {
        return <p>{__('Loading icons...', 'lcp')}</p>;  // Loading state
    }

    const iconOptions = iconData.map((icon) => ({
        value: icon.iconSvgId,  // Use icon ID as value for the SelectControl
        label: icon.name,  // Directly use the icon's name as the label
    }));
    
    
    return (
        <SelectControl
            label={__('Select Icon', 'lcp')}
            value={iconSvgId}  // Current selected icon ID
            options={iconOptions}
            onChange={handleIconChange}  // Handle icon change
        />
    );
}
