import { RangeControl, ToggleControl, PanelBody } from '@wordpress/components';
import { __ } from '@wordpress/i18n';
import ResponsiveControl from "../../ResponsiveControl";
import { useResponsiveTab } from "../../ResponsiveTabContext";

const SpacingMarginSetting = ({ attributes, setAttributes, title, initialOpen = false }) => {
  const { activeTab } = useResponsiveTab();

  const handleMarginChange = (value, position = '') => {
    const attributeName = `spacingMargin${position}${activeTab.toUpperCase()}`;
    setAttributes({ [attributeName]: value });
  };

  const renderMarginControls = () => {
    const positions = ['Top', 'Right', 'Bottom', 'Left'];
    const useIndividualAttr = `spacingMarginUseIndividual${activeTab.toUpperCase()}`;
    const useIndividual = attributes[useIndividualAttr];

    return (
      <>
        <ToggleControl
          label={__(`Use individual margin settings`, 'zenblocks')}
          checked={useIndividual}
          onChange={(value) => {
            setAttributes({ [useIndividualAttr]: value });
            if (!value) {
              const bulkValue = attributes[`spacingMargin${activeTab.toUpperCase()}`];
              positions.forEach((pos) => {
                handleMarginChange(bulkValue, pos);
              });
            }
          }}
        />
        {useIndividual ? (
          positions.map((pos) => (
            <RangeControl
              key={pos}
              label={__(`Margin ${pos} ${activeTab.toUpperCase()}`, 'zenblocks')}
              value={attributes[`spacingMargin${pos}${activeTab.toUpperCase()}`]}
              onChange={(value) => handleMarginChange(value, pos)}
              min={0}
              max={100}
            />
          ))
        ) : (
          <RangeControl
            label={__(`Margin ${activeTab.toUpperCase()}`, 'zenblocks')}
            value={attributes[`spacingMargin${activeTab.toUpperCase()}`]}
            onChange={(value) => {
              handleMarginChange(value);
              positions.forEach((pos) => {
                handleMarginChange(value, pos);
              });
            }}
            min={0}
            max={100}
          />
        )}
      </>
    );
  };

  return (
    <PanelBody title={title} initialOpen={initialOpen}>
      <ResponsiveControl initialOpen={true}>{() => renderMarginControls()}</ResponsiveControl>
    </PanelBody>
  );
};

export default SpacingMarginSetting;
