import { __ } from "@wordpress/i18n";
import SVGIconSetting, { renderSVGIcon } from "./SVGIconSetting";
import PanelBodyWithSync from "../../PanelBodyWithSync";

const IconSelectSettingV4 = ({ attributes, setAttributes, icon, iconColor, iconStrokeWidth, textColor, getCurrentIconColor, title, initialOpen = false, panelState, onTogglePanel, isHoverState = false, onSync }) => {
  const suffix = isHoverState ? "Hover" : "";

  // 内部Sync機能: 通常状態の設定をホバー状態にコピー
  const handleSyncIconSelect = () => {
    if (isHoverState) {
      setAttributes({
        iconHover: attributes.icon || '',
        iconColorHover: attributes.iconColor || '',
        iconStrokeWidthHover: attributes.iconStrokeWidth || 1.75,
      });
    } else if (onSync) {
      onSync();
    }
  };

  const currentIcon = isHoverState ? attributes.iconHover || icon : icon;
  const currentIconColor = isHoverState ? attributes.iconColorHover || iconColor : iconColor;
  const currentIconStrokeWidth = isHoverState ? attributes.iconStrokeWidthHover || iconStrokeWidth : iconStrokeWidth;
  const currentTextColor = isHoverState ? attributes.textColorHover || textColor : textColor;

  return (
    <PanelBodyWithSync title={title || __("Icon Selection", "zenblocks")} initialOpen={initialOpen || panelState} onToggle={onTogglePanel} onSync={isHoverState ? handleSyncIconSelect : undefined} className="zenblocks-nested-panel" level={2} panelType="settings" panelName="icon-select">
      <div className="zenblocks-inspector-icon-select">
        <SVGIconSetting
          value={currentIcon}
          color={getCurrentIconColor()}
          strokeWidth={currentIconStrokeWidth || 1.75}
          onChange={(value) => {
            const updates = {};
            updates[`icon${suffix}`] = value;

            if (value && value !== "" && (!currentIcon || currentIcon === "")) {
              if (!currentIconColor || currentIconColor === "") {
                updates[`iconColor${suffix}`] = currentTextColor || "";
              }
              if ((value.startsWith("lucide-") || value.startsWith("custom-svg-") || value.includes("svg") || value.includes("custom")) && !currentIconStrokeWidth) {
                updates[`iconStrokeWidth${suffix}`] = 1.75;
              }
            }

            setAttributes(updates);
          }}
          onColorChange={(value) => {
            setAttributes({
              [`iconColor${suffix}`]: value,
            });
          }}
          onStrokeWidthChange={(value) => {
            setAttributes({
              [`iconStrokeWidth${suffix}`]: value,
            });
          }}
        />
      </div>
    </PanelBodyWithSync>
  );
};

export const getCurrentIconColor = (icon, iconColor, textColor) => {
  if (!icon || icon === "") return "inherit";

  if (iconColor && iconColor !== "") {
    return iconColor;
  }

  if (textColor && textColor !== "") {
    return textColor;
  }

  return "currentColor";
};

export { renderSVGIcon };

export default IconSelectSettingV4;
