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

const IconSizeSettingV4 = ({ attributes, setAttributes, title, initialOpen = false, panelState, onTogglePanel, isHoverState = false, onSync }) => {
  const { activeTab } = useResponsiveTab();
  const suffix = isHoverState ? "Hover" : "";

  const responsiveAttrName = isHoverState ? "useResponsiveIconSizeHover" : "useResponsiveIconSize";
  const responsiveEnabled = attributes[responsiveAttrName] !== undefined ? attributes[responsiveAttrName] : false;

  const handleSizeChange = (value) => {
    if (!responsiveEnabled) {
      setAttributes({
        [`iconSizePC${suffix}`]: value,
        [`iconSizeSP${suffix}`]: value,
        ...(isHoverState ? {} : { iconSize: value }),
      });
    } else {
      const attributeName = `iconSize${activeTab.toUpperCase()}${suffix}`;
      setAttributes({ [attributeName]: value });
    }
  };

  const handleUnitChange = (value) => {
    if (!responsiveEnabled) {
      setAttributes({
        [`iconSizeUnitPC${suffix}`]: value,
        [`iconSizeUnitSP${suffix}`]: value,
        ...(isHoverState ? {} : { iconSizeUnit: value }),
      });
    } else {
      const attributeName = `iconSizeUnit${activeTab.toUpperCase()}${suffix}`;
      setAttributes({ [attributeName]: value });
    }
  };

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

    if (!value) {
      const pcSize = attributes[`iconSizePC${suffix}`] || attributes.iconSize;
      const pcUnit = attributes[`iconSizeUnitPC${suffix}`] || attributes.iconSizeUnit;
      setAttributes({
        [`iconSizeSP${suffix}`]: pcSize,
        [`iconSizeUnitSP${suffix}`]: pcUnit,
      });
    }
  };

  const renderSizeControls = (tabName) => {
    const sizeValue = attributes[`iconSize${tabName.toUpperCase()}${suffix}`] || attributes[`iconSize${suffix}`] || attributes.iconSize || 25;
    const unitValue = attributes[`iconSizeUnit${tabName.toUpperCase()}${suffix}`] || attributes[`iconSizeUnit${suffix}`] || attributes.iconSizeUnit || "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 || panelState} onToggle={onTogglePanel} onSync={onSync} className="zenblocks-nested-panel">
      <ResponsiveControl enableResponsiveToggle={true} onResponsiveToggle={handleResponsiveToggle} responsiveEnabled={responsiveEnabled}>
        {(tabName) => renderSizeControls(tabName)}
      </ResponsiveControl>
    </PanelBodyWithSync>
  );
};

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

  const { iconSize, iconSizeUnit, iconSizePC, iconSizeSP, iconSizeUnitPC, iconSizeUnitSP } = attributes;

  const safeValue = (value, fallback = null) => {
    if (value === undefined || value === null || value === 0) return fallback;
    return value;
  };

  let size, unit;

  if (device === "pc") {
    size = safeValue(iconSizePC, safeValue(iconSize));
    unit = iconSizeUnitPC || iconSizeUnit || "px";
  } else if (device === "sp") {
    size = safeValue(iconSizeSP);
    unit = iconSizeUnitSP || "px";

    if (size === null) {
      size = safeValue(iconSizePC, safeValue(iconSize));
      unit = iconSizeUnitPC || iconSizeUnit || "px";
    }
  }

  if (size === "inherit") {
    return "inherit";
  }

  if (size === null) {
    return "1em";
  }

  return `${size}${unit}`;
};

export default IconSizeSettingV4;
