// Import necessary WordPress modules.
const { SelectControl, TextControl, Button} = wp.components;

// Import device context and switcher UI for handling responsive controls.
import DeviceSwitcher from './DeviceSwitcher';
import { useDevice } from './DeviceContext';

// Default spacing structure for each device (top, right, bottom, left + unit).
const defaultSpacing = {
    top: '',
    right: '',
    bottom: '',
    left: '',
    unit: 'px'
};

/**
 * SpacingControls Component.
 *
 * Allows users to input spacing (padding/margin) values per device (responsive).
 * with optional linked/unlinked fields for top/right/bottom/left.
 *
 * Props:
 * @param {string} label - Label to display for the control.
 * @param {object} spacingValues - Object containing spacing values per device.
 * @param {function} onChange - Callback to update spacing values.
 * @param {array} allowedUnits - Units the user can choose from (default: px, %, em, rem).
 * @param {boolean} isLinked - Whether all fields are linked (same value).
 * @param {function} setIsLinked - Callback to toggle link/unlink status.
 */
const SpacingControls = ({
    label,
    spacingValues = {},
    onChange,
    allowedUnits = [ 'px', '%', 'em', 'rem' ],
    isLinked = true,
    setIsLinked
}) => {

    // Get current active device (desktop/tablet/mobile).
    const { activeDevice, setActiveDevice } = useDevice();

    // Map allowed units into SelectControl options.
    const Units = allowedUnits.map( ( unit ) => ({
        label: unit,
        value: unit
    }) );

    /**
     * Handles entire object change per device.
     */
    const handleChange = ( value ) => {
        onChange({
            ...spacingValues,
            [activeDevice]: value
        });
    };

    /**
     * Handles unit dropdown change.
     * Only allowed when current device is desktop.
     */
    const handleUnitChange = ( unit ) => {
        onChange({
            ...spacingValues,
            [activeDevice]: {
                ...spacingValues?.[activeDevice],
                unit
            }
        });
    };

    // Get spacing values for the active device, falling back to default.
    const currentValue = spacingValues[activeDevice] || defaultSpacing;

    /**
     * Handles input field value change (linked or individual).
     */
    const handleFieldChange = ( field, value ) => {
        const updated = isLinked ?
            {
                top: value,
                right: value,
                bottom: value,
                left: value,
                unit: currentValue.unit
              } :
            {
                ...currentValue,
                [field]: value
              };
        onChange({
            ...spacingValues,
            [activeDevice]: updated
        });
    };

    /**
     * Resets the spacing for the current device to default.
     */
    const handleReset = () => {
        onChange({
            ...spacingValues,
            [activeDevice]: defaultSpacing
        });
    };

    /**
     * Renders individual spacing field input (Top/Right/Bottom/Left).
     */
    const renderInput = ( label, field ) => (
        <div className="ojb-spacing-input">
            <label>{label}</label>
            <TextControl
                type="number"
                value={currentValue[field]}
                onChange={( val ) => handleFieldChange( field, val )}
                min={0}
            />
        </div>
    );
    return (

        <div className="ojb-spacing-control">
            {/* Top label row with unit selector and responsive toggle. */}
            <div className="ojb-label-wrap">
                <label className="components-base-control__label">{label}</label>

                {/* Unit dropdown (disabled for non-desktop views). */}
                <SelectControl
                    className="sel_unit"
                    value={currentValue.unit}
                    options={Units}
                    onChange={handleUnitChange}
                    disabled={'desktop' !== activeDevice}
                />

                {/* Responsive device tabs and toggle/reset buttons. */}
                <div className="ojb-responsive-tabs">
                    <div className="device-toggle-group">
                        <DeviceSwitcher/>

                        {/* Linked/unlinked toggle. */}
                        <Button
                            isSmall
                            isPressed={isLinked}
                            onClick={() => setIsLinked( ! isLinked )}
                            icon={isLinked ? 'admin-links' : 'editor-unlink'}
                            label={isLinked ? 'Linked' : 'Unlinked'}
                        />

                        {/* Reset button to default. */}
                        <Button
                            isSmall
                            icon="update"
                            label="Reset"
                            onClick={handleReset}
                        />
                    </div>
                </div>
            </div>

            {/* Spacing input fields for each side. */}
            <div className="ojb-input-wrap">
                <div className="ojb-spacing-fields">
                    {renderInput( 'Top', 'top' )}
                    {renderInput( 'Right', 'right' )}
                    {renderInput( 'Bottom', 'bottom' )}
                    {renderInput( 'Left', 'left' )}
                </div>
            </div>
        </div>
    );
};

export default SpacingControls;
