import { useBlockProps, InnerBlocks, InspectorControls } from '@wordpress/block-editor';
import {     __experimentalToggleGroupControl as ToggleGroupControl,
    __experimentalToggleGroupControlOption as ToggleGroupControlOption, __experimentalUnitControl as UnitControl, BaseControl, ToggleControl, ColorPalette, Popover, Button } from '@wordpress/components';
import { useState, useEffect } from 'react';
import { __ } from '@wordpress/i18n';

/**
 * The edit function describes the structure of your block in the context of the editor.
 * This represents what the editor will render when the block is used.
 *
 * @param {Object} props - The props for the block.
 * @return {Element} Element to render.
 */
export default function Edit({ attributes, setAttributes }) {
    const blockProps = useBlockProps();
    const { padding, maxWidthLarge, maxWidthMedium, maxWidthSmall, minHeightLarge, minHeightMedium, minHeightSmall, backgroundColor } = attributes; // Destructure necessary attributes

    // State for independent padding toggle
    const [isIndependentLarge, setIsIndependentLarge] = useState(false);

    // Toggle to show or hide the color picker popover
    const [showColorPopover, setShowColorPopover] = useState(false);
    const [selectedColor, setSelectedColor] = useState(backgroundColor || '#ffffff'); // Default color

    // Toggle padding for individual sizes
    const handleToggleChange = () => {
        setIsIndependentLarge(!isIndependentLarge);
    };

    // Update padding for all sizes
    const updatePaddingForAllSizes = (newValue) => {
        const newPadding = {
            extraLarge: { top: newValue, right: newValue, bottom: newValue, left: newValue },
            large: { top: newValue, right: newValue, bottom: newValue, left: newValue },
            medium: { top: newValue, right: newValue, bottom: newValue, left: newValue },
            small: { top: newValue, right: newValue, bottom: newValue, left: newValue }
        };
        setAttributes({ padding: newPadding });
    };

    // Handle individual padding changes
    const handlePaddingChange = (size, position, newValue) => {
        const updatedPadding = { ...padding };
        updatedPadding[size][position] = newValue;
        setAttributes({ padding: updatedPadding });
    };

    // Handle color change
    const handleColorChange = (color) => {
        setSelectedColor(color);
        setAttributes({ backgroundColor: color }); // Update background color
    };

    // Handle maxWidth change for different sizes
    const handleMaxWidthChange = (value, size) => {
        setAttributes({ [`maxWidth${size}`]: value });
    };

    // Handle minHeight change for different sizes
    const handleMinHeightChange = (value, size) => {
        setAttributes({ [`minHeight${size}`]: value });
    };

    useEffect(() => {
        console.log("Updated attributes:", attributes);
    }, [attributes]);

    return (
        <>
            <InspectorControls>
            <ToggleGroupControl
                label="my label"
                value="vertical"
                isBlock
                __nextHasNoMarginBottom
                __next40pxDefaultSize
            >
                <ToggleGroupControlOption value="horizontal" label="Horizontal" />
                <ToggleGroupControlOption value="vertical" label="Vertical" />
            </ToggleGroupControl>
                {/* BaseControl for padding */}
                <BaseControl label="Padding - Desktop">
                    <div style={{ display: 'flex', flexDirection: 'row' }}>
                        <span style={{ marginRight: '10px' }}>Padding</span>
                        <ToggleControl
                            label="Use Independent Padding"
                            checked={isIndependentLarge}
                            onChange={handleToggleChange}
                        />
                    </div>

                    {/* Padding controls */}
                    {isIndependentLarge ? (
                        <div style={{ display: 'grid', padding: '10px', gridTemplateColumns: '1fr 1fr', gap: '10px', justifyItems: 'center' }}>
                            {/* Padding controls for top, left, right, bottom */}
                            <fieldset style={{ gridColumn: 'span 2', width: '116px' }}>
                                <legend>Top</legend>
                                <UnitControl
                                    value={padding.extraLarge?.top || '10px'}
                                    onChange={(newValue) => handlePaddingChange('extraLarge', 'top', newValue)}
                                />
                            </fieldset>
                            <fieldset>
                                <legend>Left</legend>
                                <UnitControl
                                    value={padding.extraLarge?.left || '10px'}
                                    onChange={(newValue) => handlePaddingChange('extraLarge', 'left', newValue)}
                                />
                            </fieldset>
                            <fieldset>
                                <legend>Right</legend>
                                <UnitControl
                                    value={padding.extraLarge?.right || '10px'}
                                    onChange={(newValue) => handlePaddingChange('extraLarge', 'right', newValue)}
                                />
                            </fieldset>
                            <fieldset style={{ gridColumn: 'span 2', width: '116px' }}>
                                <legend>Bottom</legend>
                                <UnitControl
                                    value={padding.extraLarge?.bottom || '10px'}
                                    onChange={(newValue) => handlePaddingChange('extraLarge', 'bottom', newValue)}
                                />
                            </fieldset>
                        </div>
                    ) : (
                        <UnitControl
                            label="Padding Value"
                            value={999} // You can replace this with an attribute value
                            onChange={updatePaddingForAllSizes}
                        />
                    )}
                </BaseControl>

                {/* Max Width Controls */}
                <BaseControl label="Max Width">
                    <div style={{ display: 'flex', flexDirection: 'column' }}>
                        <UnitControl
                            label="Large"
                            value={maxWidthLarge}
                            onChange={(value) => handleMaxWidthChange(value, 'Large')}
                            defaultUnit="px"
                        />
                        <UnitControl
                            label="Medium"
                            value={maxWidthMedium}
                            onChange={(value) => handleMaxWidthChange(value, 'Medium')}
                            defaultUnit="px"
                        />
                        <UnitControl
                            label="Small"
                            value={maxWidthSmall}
                            onChange={(value) => handleMaxWidthChange(value, 'Small')}
                            defaultUnit="px"
                        />
                    </div>
                </BaseControl>

                {/* Min Height Controls */}
                <BaseControl label="Min Height">
                    <div style={{ display: 'flex', flexDirection: 'column' }}>
                        <UnitControl
                            label="Large"
                            value={minHeightLarge}
                            onChange={(value) => handleMinHeightChange(value, 'Large')}
                            defaultUnit="px"
                        />
                        <UnitControl
                            label="Medium"
                            value={minHeightMedium}
                            onChange={(value) => handleMinHeightChange(value, 'Medium')}
                            defaultUnit="px"
                        />
                        <UnitControl
                            label="Small"
                            value={minHeightSmall}
                            onChange={(value) => handleMinHeightChange(value, 'Small')}
                            defaultUnit="px"
                        />
                    </div>
                </BaseControl>

                {/* Background color picker */}
                <BaseControl label={__('Background Color')}>
                    <div>
                        <Button onClick={() => setShowColorPopover(!showColorPopover)}>
                            {__('Choose Background Color')}
                        </Button>

                        {showColorPopover && (
                            <Popover position="bottom center">
                                <ColorPalette
                                    value={selectedColor}
                                    onChange={handleColorChange}
                                    colors={[{ name: "Primary", slug: "primary", color: "#3E5062" }, { name: "Secondary", slug: "secondary", color: "#2B3843" }, { name: "Light Color - 1", slug: "light-color-1", color: "#ECF0F5" }, { name: "Dark Gray", slug: "dark-gray", color: "#333333" }, { name: "Accent", slug: "accent", color: "#61FFB6" }]}
                                    disableCustomColors={false}
                                />
                            </Popover>
                        )}

                        {/* Color indicator */}
                        <div style={{ backgroundColor: selectedColor, width: '30px', height: '30px', marginTop: '10px', borderRadius: '50%' }}></div>
                    </div>
                </BaseControl>
            </InspectorControls>

            <div {...blockProps} style={{ maxWidth: maxWidthLarge, minHeight: minHeightLarge }}>
                <InnerBlocks />
            </div>
        </>
    );
}
