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

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

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

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

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

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

export default SpacingPaddingSetting;
