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

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

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

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

  const renderHeightControl = (tabName) => {
    const useCustomHeight = attributes[`layoutHeightUseCustom${tabName.toUpperCase()}`];

    return (
      <div>
        <ToggleControl
          label={__(`Use custom height`, 'zenblocks')}
          checked={useCustomHeight}
          onChange={(value) => {
            setAttributes({ [`layoutHeightUseCustom${tabName.toUpperCase()}`]: value });
          }}
        />
        {useCustomHeight && (
          <>
            <RangeControl
              label={__(`Height ${tabName.toUpperCase()}`, 'zenblocks')}
              value={parseFloat(attributes[`layoutHeight${tabName.toUpperCase()}`])}
              onChange={(value) => handleHeightChange(value.toString())}
              min={0}
              max={1000}
              step={1}
            />
            <SelectControl
              label={__('Unit', 'zenblocks')}
              value={attributes[`layoutHeightUnit${tabName.toUpperCase()}`]}
              options={[
                { label: 'px', value: 'px' },
                { label: '%', value: '%' },
                { label: 'vh', value: 'vh' },
              ]}
              onChange={(value) => handleUnitChange(value)}
            />
          </>
        )}
      </div>
    );
  };

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

export default LayoutHeightSetting;
