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';
import { DimensionValueControl } from '../components/DimensionValueControl';

export default function Edit(props) {
    const { attributes, setAttributes } = props;
    const { buttonAction, iconHeight, 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) {
            setAttributes({
                iconSvgPath: selectedIcon.iconSvgPath,
                iconSvgId: selectedIcon.iconSvgId,
                iconSvgViewbox: selectedIcon.viewbox
            });
        }
    };

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

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

    const handlePaddingChange = (value) => {
        if (typeof value === 'number') {
            value = `${value}px`; 
        }
        setAttributes({ buttonPadding: value });
    };

    // Handle changes to icon height (from the DimensionValueControl)
    const handleIconHeightChange = (newHeight) => {
        console.log("New icon height:", newHeight); // Debugging line
        setAttributes({ iconHeight: newHeight });  // Update the iconHeight attribute
    };

    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")}>
                    <PaddingControl
                        onChange={handlePaddingChange}
                    />
                    <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}
                    />
                    <DimensionValueControl
                        value={iconHeight}  // Pass the current iconHeight to the DimensionValueControl
                        onChange={(newHeight) => setAttributes({ iconHeight: newHeight })}  // Update iconHeight when it changes
                        includeAuto={true}
                        autoReturnsNull={true}
                    />
                    {displayIcon && (
                        <>
                            <SelectControl
                                label={__("Icon Source")}
                                value={iconSource}
                                options={iconSourceOptions}
                                onChange={(value) => setAttributes({ iconSource: value })}
                            />
                            {iconSource === 'manualSvgPath' && (
                                <TextareaControl
                                    label="Icon SVG Path"
                                    value={iconSvgPath}
                                    onChange={(value) => setAttributes({ iconSvgPath: value })}
                                />
                            )}
                            {iconSource === 'iconSelector' && (
                                <IconSelectControl
                                    iconSvgId={iconSvgId}
                                    onIconChange={handleIconChanges}
                                />
                            )}
                        </>
                    )}
                </PanelBody>
            </InspectorControls>

            <div {...useBlockProps()}>
                {buttonAction === 'customUrl' ? (
                    <a href={customUrl} className="lcp-button" style={{ padding: buttonPadding || '10px' }}>
                        {displayIcon && iconSvgPath && (
                            <svg style={{ height: iconHeight }} className="lcp-icon" xmlns="http://www.w3.org/2000/svg" viewBox={iconSvgViewbox || "0 0 576 576"} dangerouslySetInnerHTML={{ __html: iconSvgPath }} />
                        )}
                        <span className="lcp-button-text">
                            {buttonText || 'Button'}
                        </span>
                    </a>
                ) : (
                    <button className="lcp-button" style={{ padding: buttonPadding || '10px' }}>
                        {displayIcon && iconSvgPath && (
                            <svg style={{ height: iconHeight }} className="lcp-icon" xmlns="http://www.w3.org/2000/svg" viewBox={iconSvgViewbox || "0 0 576 576"} dangerouslySetInnerHTML={{ __html: iconSvgPath }} />
                        )}
                        <span className="lcp-button-text">
                            {buttonText || 'Button'}
                        </span>
                    </button>
                )}
            </div>
        </>
    );
}
