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

const getDefaultIconColor = () => ({
  pc: { color: "", alpha: 1 },
  md: { color: "", alpha: 1 },
  tb: { color: "", alpha: 1 },
  sp: { color: "", alpha: 1 },
});

const IconColorSettingV7 = ({
  attributes,
  setAttributes,
  title,
  opened,
  onToggle,
  isHoverState = false,
  onSync,
}) => {
  const suffix = isHoverState ? "Hover" : "";
  const attrName = `iconColorV2${suffix}`;
  const responsiveAttrName = `useResponsiveIconColor${suffix}`;
  const responsiveEnabled = attributes[responsiveAttrName] !== undefined ? attributes[responsiveAttrName] : false;
  const { activeTab } = useResponsiveTabV2();
  const enabledBreakpoints = getEnabledBreakpoints();

  const iconColorData = attributes[attrName] || getDefaultIconColor();

  // 内部Sync機能: 通常状態の設定をホバー状態にコピー
  const handleSyncIconColor = () => {
    if (isHoverState) {
      const normalData = attributes.iconColorV2 || getDefaultIconColor();
      const normalResponsive = attributes.useResponsiveIconColor || false;
      setAttributes({
        iconColorV2Hover: JSON.parse(JSON.stringify(normalData)),
        useResponsiveIconColorHover: normalResponsive,
      });
    } else if (onSync) {
      onSync();
    }
  };

  const handleChange = (key, value) => {
    const newData = JSON.parse(JSON.stringify(iconColorData));
    if (responsiveEnabled) {
      newData[activeTab][key] = value;
    } else {
      enabledBreakpoints.forEach((bp) => {
        newData[bp][key] = value;
      });
    }
    setAttributes({ [attrName]: newData });
  };

  const handleResponsiveToggle = (value) => {
    const newData = JSON.parse(JSON.stringify(iconColorData));
    const emptyBpData = { color: "", alpha: 1 };

    if (value) {
      enabledBreakpoints.forEach((bp) => {
        if (bp !== "pc") {
          newData[bp] = { ...emptyBpData };
        }
      });
    } else {
      const pcData = newData.pc || getDefaultIconColor().pc;
      enabledBreakpoints.forEach((bp) => {
        newData[bp] = { ...pcData };
      });
    }

    setAttributes({
      [responsiveAttrName]: value,
      [attrName]: newData,
    });
  };

  const renderControls = (tabName) => {
    const tabData = iconColorData[tabName] || getDefaultIconColor().pc;
    const currentColor = tabData.color || "";
    const currentAlpha = tabData.alpha !== undefined ? tabData.alpha : 1;

    return (
      <CustomColorPalette
        color={currentColor}
        alpha={currentAlpha}
        enableGradient={false}
        enableAlpha={true}
        enableAddButton={true}
        onColorChange={(value) => handleChange("color", value || "")}
        onAlphaChange={(value) => handleChange("alpha", value)}
      />
    );
  };

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

export const getIconColorValue = (attributes, device = "pc", isHover = false) => {
  const attrName = isHover ? "iconColorV2Hover" : "iconColorV2";
  const data = attributes[attrName];
  if (!data) return null;

  const enabledBreakpoints = getEnabledBreakpoints();
  const currentIndex = enabledBreakpoints.indexOf(device);

  for (let i = currentIndex; i >= 0; i--) {
    const bp = enabledBreakpoints[i];
    const bpData = data[bp];
    if (bpData && bpData.color && bpData.color !== "") {
      const alpha = bpData.alpha !== undefined ? bpData.alpha : 1;
      if (alpha < 1) {
        return hexToRgba(bpData.color, alpha);
      }
      return bpData.color;
    }
  }
  return null;
};

export const getDirectIconColor = (attributes, device = "pc", isHover = false) => {
  const attrName = isHover ? "iconColorV2Hover" : "iconColorV2";
  const data = attributes[attrName];
  if (!data || !data[device]) return null;

  const bpData = data[device];
  if (bpData.color && bpData.color !== "") {
    const alpha = bpData.alpha !== undefined ? bpData.alpha : 1;
    if (alpha < 1) {
      return hexToRgba(bpData.color, alpha);
    }
    return bpData.color;
  }
  return null;
};

export default IconColorSettingV7;
