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

const LayoutWidthSettingV3 = ({
  attributes,
  setAttributes,
  title,
  initialOpen = false,
  maxWidth = 2000,
  maxMinWidth = 2000,
  maxMaxWidth = 2000,
  minWidth = 0,
  minMinWidth = 0,
  minMaxWidth = 0,
  step = 1,
  stepMinWidth = 1,
  stepMaxWidth = 1,
}) => {
  const { activeTab } = useResponsiveTab();

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

  const handleUnitChange = (type, value, deviceTab) => {
    const attributeName = `layoutWidth${type}Unit${deviceTab.toUpperCase()}`;
    setAttributes({ [attributeName]: value });
    
    // fillが選択された場合、数値を0にクリア
    if (value === "fill") {
      const valueAttributeName = `layoutWidth${type}${deviceTab.toUpperCase()}`;
      setAttributes({ [valueAttributeName]: 0 });
    }
  };

  const renderWidthControls = (tabName) => {
    // Normal Width Controls
    const useCustomWidth = attributes[`layoutWidthUseCustom${tabName.toUpperCase()}`];
    // Min Width Controls
    const useCustomMinWidth = attributes[`layoutWidthMinUseCustom${tabName.toUpperCase()}`];
    // Max Width Controls
    const useCustomMaxWidth = attributes[`layoutWidthMaxUseCustom${tabName.toUpperCase()}`];

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

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

    const renderWidthControl = (type, useCustom) => {
      const labelName = type ? `${type} Width` : "Width";
      const currentUnit = attributes[`layoutWidth${type}Unit${tabName.toUpperCase()}`] || "px";
      const isFillSelected = currentUnit === "fill";
      
      return (
        <div className="layout-width-control" style={{ marginBottom: "16px" }}>
          <ToggleControl
            label={getLabel(type)}
            checked={useCustom}
            onChange={(value) => {
              setAttributes({ [`layoutWidth${type}UseCustom${tabName.toUpperCase()}`]: value });
              
              // ONにした時に初期値を設定（まだ値が設定されていない場合）
              if (value) {
                const currentValue = attributes[`layoutWidth${type}${tabName.toUpperCase()}`];
                const currentUnit = attributes[`layoutWidth${type}Unit${tabName.toUpperCase()}`];
                
                if (currentValue === undefined || currentValue === null) {
                  const defaultValue = type === "" ? 100 : type === "Min" ? 0 : 100;
                  setAttributes({ [`layoutWidth${type}${tabName.toUpperCase()}`]: defaultValue });
                }
                
                if (!currentUnit) {
                  const defaultUnit = type === "" ? "%" : "px";
                  setAttributes({ [`layoutWidth${type}Unit${tabName.toUpperCase()}`]: defaultUnit });
                }
              }
            }}
          />
          
          {useCustom && (
            <>
              <div className="layout-width-label">
                {__(`${labelName} ${tabName.toUpperCase()}`, "zenblocks")}
                {isFillSelected && (
                  <span style={{ 
                    marginLeft: "8px", 
                    fontSize: "12px", 
                    color: "#666", 
                    fontStyle: "italic" 
                  }}>
                    {__("(fills remaining space)", "zenblocks")}
                  </span>
                )}
              </div>
              <div className="layout-width-controls">
                <RangeControl
                  value={parseFloat(attributes[`layoutWidth${type}${tabName.toUpperCase()}`]) || (type === "" ? 100 : type === "Min" ? 0 : 100)}
                  onChange={(value) => handleValueChange(type, value, tabName)}
                  min={type === "" ? minWidth : type === "Min" ? minMinWidth : minMaxWidth}
                  max={type === "" ? maxWidth : type === "Min" ? maxMinWidth : maxMaxWidth}
                  step={type === "" ? step : type === "Min" ? stepMinWidth : stepMaxWidth}
                  disabled={isFillSelected}
                  style={{
                    opacity: isFillSelected ? 0.5 : 1,
                    pointerEvents: isFillSelected ? "none" : "auto"
                  }}
                />
                <SelectControl
                  value={currentUnit}
                  options={unitOptions}
                  onChange={(value) => handleUnitChange(type, value, tabName)}
                  className="unit-select"
                />
              </div>
              {isFillSelected && (
                <div style={{ 
                  fontSize: "12px", 
                  color: "#666", 
                  marginTop: "4px",
                  fontStyle: "italic"
                }}>
                  {__("* Numeric settings are disabled when fill is selected", "zenblocks")}
                </div>
              )}
            </>
          )}
        </div>
      );
    };

    return (
      <div>
        {/* Width Controls */}
        {renderWidthControl("", useCustomWidth)}

        {/* Min Width Controls */}
        {renderWidthControl("Min", useCustomMinWidth)}

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

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

          .layout-width-label {
            margin-bottom: 8px;
            display: flex;
            align-items: center;
          }

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

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

export default LayoutWidthSettingV3;