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

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

  const handleWidthChange = (value) => {
    const attributeName = `layoutWidth${activeTab.toUpperCase()}`;
    setAttributes({ [attributeName]: value });
  };

  const handleUnitChange = (value) => {
    const attributeName = `layoutWidthUnit${activeTab.toUpperCase()}`;
    setAttributes({ [attributeName]: value });
  };

  const renderWidthControl = (tabName) => {
    const useCustomWidth = attributes[`layoutWidthUseCustom${tabName.toUpperCase()}`];

    return (
      <div>
        <ToggleControl
          label={__(`Use custom width`, 'zenblocks')}
          checked={useCustomWidth}
          onChange={(value) => {
            setAttributes({ [`layoutWidthUseCustom${tabName.toUpperCase()}`]: value });
          }}
        />
        {useCustomWidth && (
          <>
            <RangeControl
              label={__(`Width ${tabName.toUpperCase()}`, 'zenblocks')}
              value={parseFloat(attributes[`layoutWidth${tabName.toUpperCase()}`])}
              onChange={(value) => handleWidthChange(value.toString())}
              min={0}
              max={100}
              step={1}
            />
            <SelectControl
              label={__('Unit', 'zenblocks')}
              value={attributes[`layoutWidthUnit${tabName.toUpperCase()}`]}
              options={[
                { label: 'px', value: 'px' },
                { label: '%', value: '%' },
                { label: 'vw', value: 'vw' },
              ]}
              onChange={(value) => handleUnitChange(value)}
            />
          </>
        )}
      </div>
    );
  };

  return (
    <PanelBody title={title} initialOpen={initialOpen}>
      <ResponsiveControl>{(tabName) => renderWidthControl(tabName)}</ResponsiveControl>
    </PanelBody>
  );
};

export default LayoutWidthSetting;
