import { __ } from "@wordpress/i18n";
import { RangeControl, SelectControl } from "@wordpress/components";
import ResponsiveControlV2 from "../../ResponsiveControlV2";
import { useResponsiveTabV2 } from "../../ResponsiveTabContextV2";
import PanelBodyWithSync from "../../PanelBodyWithSync";
import { getEnabledBreakpoints } from "../../../../../core/breakpoints";

const getDefaultIconSize = () => ({
  pc: { value: "", unit: "px" },
  md: { value: "", unit: "px" },
  tb: { value: "", unit: "px" },
  sp: { value: "", unit: "px" }
});

const IconSizeSettingV5 = ({ 
  attributes, 
  setAttributes, 
  title, 
  initialOpen = false, 
  opened,
  onToggle,
  onSync,
  isHoverState = false, 
  supportsHover = true 
}) => {
  const effectiveHoverState = supportsHover ? isHoverState : false;
  const v2Key = effectiveHoverState ? "iconSizeV2Hover" : "iconSizeV2";
  const responsiveAttrName = effectiveHoverState ? "useResponsiveIconSizeHover" : "useResponsiveIconSize";
  const responsiveEnabled = attributes[responsiveAttrName] !== undefined ? attributes[responsiveAttrName] : false;
  const { activeTab } = useResponsiveTabV2();
  const enabledBreakpoints = getEnabledBreakpoints();

  const iconSizeData = attributes[v2Key] || getDefaultIconSize();

  // 内部Sync機能: 通常状態の設定をホバー状態にコピー
  const handleSyncIconSize = () => {
    if (effectiveHoverState) {
      const normalData = attributes.iconSizeV2 || getDefaultIconSize();
      const normalResponsive = attributes.useResponsiveIconSize || false;
      setAttributes({
        iconSizeV2Hover: JSON.parse(JSON.stringify(normalData)),
        useResponsiveIconSizeHover: normalResponsive,
      });
    } else if (onSync) {
      onSync();
    }
  };

  const handleSizeChange = (value) => {
    const newIconSize = { ...iconSizeData };
    if (!responsiveEnabled) {
      enabledBreakpoints.forEach((bp) => {
        newIconSize[bp] = { ...newIconSize[bp], value: value };
      });
    } else {
      newIconSize[activeTab] = { ...newIconSize[activeTab], value: value };
    }
    setAttributes({ [v2Key]: newIconSize });
  };

  const handleUnitChange = (value) => {
    const newIconSize = { ...iconSizeData };
    if (!responsiveEnabled) {
      enabledBreakpoints.forEach((bp) => {
        newIconSize[bp] = { ...newIconSize[bp], unit: value };
      });
    } else {
      newIconSize[activeTab] = { ...newIconSize[activeTab], unit: value };
    }
    setAttributes({ [v2Key]: newIconSize });
  };

  const handleResponsiveToggle = (value) => {
    setAttributes({ [responsiveAttrName]: value });

    const newIconSize = { ...iconSizeData };
    const pcData = newIconSize.pc;
    enabledBreakpoints.forEach((bp) => {
      if (bp !== 'pc') {
        newIconSize[bp] = { ...pcData };
      }
    });
    setAttributes({ [v2Key]: newIconSize });
  };

  const renderSizeControls = (tabName) => {
    const tabData = iconSizeData[tabName] || { value: "", unit: "px" };
    const sizeValue = tabData.value !== "" ? tabData.value : 25;
    const unitValue = tabData.unit || "px";

    return (
      <div style={{ display: "flex", alignItems: "flex-end", gap: "8px" }}>
        <div style={{ flex: 1 }}>
          <RangeControl value={sizeValue} onChange={handleSizeChange} min={12} max={250} step={1} />
        </div>
        <div style={{ minWidth: "40px" }}>
          <SelectControl
            value={unitValue}
            options={[
              { label: "px", value: "px" },
              { label: "em", value: "em" },
              { label: "rem", value: "rem" },
            ]}
            onChange={handleUnitChange}
          />
        </div>
      </div>
    );
  };

  return (
    <PanelBodyWithSync 
      title={title || __("Icon Size", "zenblocks")} 
      initialOpen={initialOpen} 
      opened={opened}
      onToggle={onToggle}
      onSync={effectiveHoverState ? handleSyncIconSize : undefined}
      className="zenblocks-nested-panel"
      level={2}
      panelType="settings"
      panelName="icon-size"
    >
      <div className="zenblocks-inspector-icon-size">
        <ResponsiveControlV2
          initialOpen={true}
          enableResponsiveToggle={true}
          responsiveEnabled={responsiveEnabled}
          onResponsiveToggle={handleResponsiveToggle}
          attributes={attributes}
          setAttributes={setAttributes}
          syncAttributeName={responsiveAttrName}
        >
          {(tabName) => renderSizeControls(tabName)}
        </ResponsiveControlV2>
      </div>
    </PanelBodyWithSync>
  );
};

export const getIconSizeValue = (attributes, device = "pc", isHoverState = false) => {
  if (!attributes) return "inherit";

  const v2Key = isHoverState ? "iconSizeV2Hover" : "iconSizeV2";
  const iconSizeData = attributes[v2Key];

  if (iconSizeData && iconSizeData[device]) {
    const { value, unit } = iconSizeData[device];
    if (value !== undefined && value !== null && value !== "" && value !== 0) {
      return `${value}${unit || "px"}`;
    }
  }

  return "";
};

// Get icon size with inheritance from upper breakpoints
export const getIconSizeWithInheritance = (attributes, device = "pc", isHoverState = false) => {
  if (!attributes) return "";
  const enabledBreakpoints = getEnabledBreakpoints();
  const v2Key = isHoverState ? "iconSizeV2Hover" : "iconSizeV2";
  const iconSizeData = attributes[v2Key];

  if (!iconSizeData) return "";

  const currentIndex = enabledBreakpoints.indexOf(device);
  for (let i = currentIndex; i >= 0; i--) {
    const bp = enabledBreakpoints[i];
    if (iconSizeData[bp]) {
      const { value, unit } = iconSizeData[bp];
      if (value !== undefined && value !== null && value !== "" && value !== 0) {
        return `${value}${unit || "px"}`;
      }
    }
  }

  return "";
};

export const getDirectIconSize = (attributes, device = "pc", isHoverState = false) => {
  if (!attributes) return undefined;

  const v2Key = isHoverState ? "iconSizeV2Hover" : "iconSizeV2";
  const iconSizeData = attributes[v2Key];

  if (iconSizeData && iconSizeData[device]) {
    const { value, unit } = iconSizeData[device];
    if (value !== undefined && value !== null && value !== "" && value !== 0) {
      return `${value}${unit || "px"}`;
    }
  }

  return undefined;
};

export const getIconSizeValueHover = (attributes, device = "pc") => {
  return getIconSizeValue(attributes, device, true);
};

export const getIconSizeHoverWithInheritance = (attributes, device = "pc") => {
  return getIconSizeWithInheritance(attributes, device, true);
};

export default IconSizeSettingV5;
