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

const LayoutHeightSettingV2 = ({ 
  attributes, 
  setAttributes, 
  title, 
  initialOpen = false,
  maxHeight = 2000,
  maxMinHeight = 2000,
  maxMaxHeight = 2000,
  minHeight = 0,
  minMinHeight = 0,
  minMaxHeight = 0,
  step = 1,
  stepMinHeight = 1,
  stepMaxHeight = 1,
}) => {
  const { activeTab } = useResponsiveTab();

  const handleValueChange = (type, value, deviceTab) => {
    const attributeName = `layoutHeight${type}${deviceTab.toUpperCase()}`;
    // Number型として保存
    setAttributes({ [attributeName]: value });
  };

  const handleUnitChange = (type, value, deviceTab) => {
    const attributeName = `layoutHeight${type}Unit${deviceTab.toUpperCase()}`;
    setAttributes({ [attributeName]: value });
  };

  const renderHeightControls = (tabName) => {
    // Normal Height Controls
    const useCustomHeight = attributes[`layoutHeightUseCustom${tabName.toUpperCase()}`];
    // Min Height Controls
    const useCustomMinHeight = attributes[`layoutHeightMinUseCustom${tabName.toUpperCase()}`];
    // Max Height Controls
    const useCustomMaxHeight = attributes[`layoutHeightMaxUseCustom${tabName.toUpperCase()}`];

    const unitOptions = [
      { label: "px", value: "px" },
      { label: "%", value: "%" },
      { label: "vh", value: "vh" },
    ];

    const getLabel = (type) => {
      const prefix = type ? `${type} Height` : "Height";
      return `Use ${prefix.toLowerCase()}`;
    };

    const renderHeightControl = (type, useCustom) => {
      const labelName = type ? `${type} Height` : "Height";
      
      return (
        <div className="layout-height-control" style={{ marginBottom: "16px" }}>
          <ToggleControl
            label={getLabel(type)}
            checked={useCustom}
            onChange={(value) => {
              setAttributes({ [`layoutHeight${type}UseCustom${tabName.toUpperCase()}`]: value });
              
              // ONにした時に初期値を設定（まだ値が設定されていない場合）
              if (value) {
                const currentValue = attributes[`layoutHeight${type}${tabName.toUpperCase()}`];
                const currentUnit = attributes[`layoutHeight${type}Unit${tabName.toUpperCase()}`];
                
                if (currentValue === undefined || currentValue === null) {
                  const defaultValue = type === "" ? 100 : type === "Min" ? 0 : 100;
                  setAttributes({ [`layoutHeight${type}${tabName.toUpperCase()}`]: defaultValue });
                }
                
                if (!currentUnit) {
                  setAttributes({ [`layoutHeight${type}Unit${tabName.toUpperCase()}`]: "px" });
                }
              }
            }}
          />
          
          {useCustom && (
            <>
              <div className="layout-height-label">
                {__(`${labelName} ${tabName.toUpperCase()}`, "zenblocks")}
              </div>
              <div className="layout-height-controls">
                <RangeControl
                  value={attributes[`layoutHeight${type}${tabName.toUpperCase()}`] || (type === "" ? 100 : type === "Min" ? 0 : 100)}
                  onChange={(value) => handleValueChange(type, value, tabName)}
                  min={type === "" ? minHeight : type === "Min" ? minMinHeight : minMaxHeight}
                  max={type === "" ? maxHeight : type === "Min" ? maxMinHeight : maxMaxHeight}
                  step={type === "" ? step : type === "Min" ? stepMinHeight : stepMaxHeight}
                />
                <SelectControl
                  value={attributes[`layoutHeight${type}Unit${tabName.toUpperCase()}`] || "px"}
                  options={unitOptions}
                  onChange={(value) => handleUnitChange(type, value, tabName)}
                  className="unit-select"
                />
              </div>
            </>
          )}
        </div>
      );
    };

    return (
      <div>
        {/* Height Controls */}
        {renderHeightControl("", useCustomHeight)}

        {/* Min Height Controls */}
        {renderHeightControl("Min", useCustomMinHeight)}

        {/* Max Height Controls */}
        {renderHeightControl("Max", useCustomMaxHeight)}
        
        {/* CSS styles for proper spacing and layout */}
        <style>
          {`
          .layout-height-control
          .components-base-control{
            padding-top: 0 !important;
            margin-bottom: 0.5em !important;
          }

          .layout-height-control
          .components-base-control
          .components-base-control{
            padding-left: 0 !important;
            padding-right: 0 !important;
          }

          .layout-height-label {
            margin-bottom: 8px;
          }

          .layout-height-controls {
            display: flex;
            align-items: flex-start;
          }
          
          .layout-height-controls .components-range-control {
            flex: 1;
          }
          
          .layout-height-controls .unit-select {
            flex: 0 0 70px;
            margin-left: 8px;
          }
          `}
        </style>
      </div>
    );
  };

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

export default LayoutHeightSettingV2;