import { __ } from '@wordpress/i18n';
import { useBlockProps, InspectorControls } from '@wordpress/block-editor';
import { PanelBody, SelectControl, TextControl, TextareaControl, ToggleControl } from '@wordpress/components';
import { useState, useEffect } from '@wordpress/element';
import './editor.scss';
import { IconSelectControl } from '../components/IconSelectControl';
import { PaddingControl } from '../components/PaddingControl';

export default function Edit(props) {
    const { attributes, setAttributes } = props;
    const { buttonAction, buttonText, iconSvgId, iconSvgPath, iconSvgViewbox, displayIcon, iconSource, customUrl, buttonPadding } = attributes;

    // Handle icon selection from dropdown
    const handleIconChanges = (selectedIcon) => {
        console.log("Icon changed:", selectedIcon);
        if (selectedIcon && selectedIcon.iconSvgPath) {
            console.log("Selected Icon Path: ", selectedIcon.iconSvgPath);  // Log the selected icon path for debugging
            console.log("Selected Icon Viewbox: ", selectedIcon.viewbox);  // Log the selected icon viewbox for debugging
            setAttributes({
                iconSvgPath: selectedIcon.iconSvgPath,  // Set the SVG path in the attributes
                iconSvgId: selectedIcon.iconSvgId,      // Set the icon ID
                iconSvgViewbox: selectedIcon.viewbox    // Set the icon viewbox in the attributes
            });
        }
    };

    const handleToggleChange = (value) => {
        setAttributes({ displayIcon: value });
    };

    const handleCustomUrlChange = (value) => {
        setAttributes({ customUrl: value });
    };

    const handlePaddingChange = (value) => {
        // If the padding value is a number, make sure to append 'px' to it
        if (typeof value === 'number') {
            value = `${value}px`;  // Convert to string with 'px'
        }
        setAttributes({ buttonPadding: value });
    };

    const iconSourceOptions = [
        { value: 'manualSvgPath', label: 'SVG Path' },
        { value: 'iconSelector', label: 'Icon Library' },
    ];

    const buttonActionOptions = [
        { value: 'customUrl', label: 'Custom URL' },
        { value: 'showLoginForm', label: 'Show Login Form' },
        { value: 'logOut', label: 'Open Popup' },
        { value: 'shareCurrentPost', label: 'Share Current Post' },
        { value: 'displaySidecontent', label: 'Display Sidecontent' }
    ];

    return (
        <>
            <InspectorControls>
                <PanelBody title={__("Button Settings")}>
                    {/* Pass the necessary props to PaddingControl */}
                    <PaddingControl

                    />
                    {/* Button Action */}
                    <SelectControl
                        label={__("Button Action")}
                        value={buttonAction}
                        options={buttonActionOptions}
                        onChange={(value) => setAttributes({ buttonAction: value })}
                    />
                    {buttonAction === 'customUrl' && (
                        <TextControl
                            label={__("Custom URL")}
                            value={customUrl}
                            onChange={handleCustomUrlChange}
                        />
                    )}
                    <TextControl
                        label={__("Button Text")}
                        value={buttonText}
                        onChange={(value) => setAttributes({ buttonText: value })}
                    />
                    <ToggleControl
                        label="Display Icon"
                        checked={displayIcon}
                        onChange={handleToggleChange}
                    />
                    {displayIcon && (
                        <>
                            <SelectControl
                                label={__("Icon Source")}
                                value={iconSource}
                                options={iconSourceOptions}
                                onChange={(value) => setAttributes({ iconSource: value })}
                            />
                            {iconSource === 'manualSvgPath' && (
                                <TextareaControl
                                    label="Icon SVG Path"
                                    value={iconSvgPath} // Use the correct attribute `iconSvgPath`
                                    onChange={(value) => setAttributes({ iconSvgPath: value })}
                                />
                            )}
                            {iconSource === 'iconSelector' && (
                                <IconSelectControl
                                    iconSvgId={iconSvgId} // Pass current iconSvgId
                                    onIconChange={handleIconChanges} // Handle icon selection
                                />
                            )}
                        </>
                    )}
                </PanelBody>
            </InspectorControls>

            <div {...useBlockProps()}>
                {buttonAction === 'customUrl' ? (
                    // Render an anchor tag if buttonAction is 'customUrl'
                    <a href={customUrl} className="lcp-button" style={{ padding: buttonPadding || '10px' }}>
                        {/* Conditionally render the icon if displayIcon is true and iconSvgPath is available */}
                        {displayIcon && iconSvgPath && (
                            <svg className="lcp-icon" xmlns="http://www.w3.org/2000/svg" viewBox={iconSvgViewbox || "0 0 576 576"} dangerouslySetInnerHTML={{ __html: iconSvgPath }} />
                        )}
                        {/* Render the button text */}
                        {buttonText || 'Button'} {/* Use buttonText or fallback */}
                    </a>
                ) : (
                    // Render a button if buttonAction is not 'customUrl'
                    <button className="lcp-button" style={{ padding: buttonPadding || '10px' }}>
                        {/* Conditionally render the icon if displayIcon is true and iconSvgPath is available */}
                        {displayIcon && iconSvgPath && (
                            <svg className="lcp-icon" xmlns="http://www.w3.org/2000/svg" viewBox={iconSvgViewbox || "0 0 576 576"} dangerouslySetInnerHTML={{ __html: iconSvgPath }} />
                        )}
                        {/* Render the button text */}
                        {buttonText || 'Button'} {/* Use buttonText or fallback */}
                    </button>
                )}
            </div>
        </>
    );
}
