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

const IconFrameColorSettingV4 = ({
  attributes,
  setAttributes,
  title,
  initialOpen = false,
  panelState,
  onTogglePanel,
  isHoverState = false,
  onSync,
  supportsHover = true
}) => {
  const effectiveHoverState = supportsHover ? isHoverState : false;
  const suffix = effectiveHoverState ? "Hover" : "";
  const responsiveAttrName = effectiveHoverState ? "useResponsiveIconFrameColorHover" : "useResponsiveIconFrameColor";
  const responsiveEnabled = attributes[responsiveAttrName] !== undefined ? attributes[responsiveAttrName] : false;
  const { activeTab } = useResponsiveTabV2();
  const enabledBreakpoints = getEnabledBreakpoints();

  // 内部Sync機能: 通常状態の設定をホバー状態にコピー
  const handleSyncIconFrameColor = () => {
    if (effectiveHoverState) {
      const syncAttrs = {};
      // ベース属性（デバイスサフィックスなし）を同期
      syncAttrs.iconFrameBgColorHover = attributes.iconFrameBgColor;
      syncAttrs.iconFrameBgColorAlphaHover = attributes.iconFrameBgColorAlpha;
      // デバイス別属性を同期
      enabledBreakpoints.forEach((bp) => {
        const bpUpper = bp.toUpperCase();
        syncAttrs[`iconFrameBgColor${bpUpper}Hover`] = attributes[`iconFrameBgColor${bpUpper}`];
        syncAttrs[`iconFrameBgColorAlpha${bpUpper}Hover`] = attributes[`iconFrameBgColorAlpha${bpUpper}`];
        syncAttrs[`iconFrameBgGradient${bpUpper}Hover`] = attributes[`iconFrameBgGradient${bpUpper}`];
        syncAttrs[`iconFrameBgUseGradient${bpUpper}Hover`] = attributes[`iconFrameBgUseGradient${bpUpper}`];
      });
      syncAttrs.useResponsiveIconFrameColorHover = attributes.useResponsiveIconFrameColor || false;
      setAttributes(syncAttrs);
    } else if (onSync) {
      onSync();
    }
  };

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

    // PCの値を他のブレークポイントにコピー
    const syncAttrs = {};
    const pcColor = attributes[`iconFrameBgColorPC${suffix}`] || attributes[`iconFrameBgColor${suffix}`] || attributes.iconFrameBgColor;
    const pcAlpha = attributes[`iconFrameBgColorAlphaPC${suffix}`] ?? attributes[`iconFrameBgColorAlpha${suffix}`] ?? attributes.iconFrameBgColorAlpha ?? 1;
    const pcGradient = attributes[`iconFrameBgGradientPC${suffix}`] || attributes[`iconFrameBgGradient${suffix}`] || attributes.iconFrameBgGradient || "";
    const pcUseGradient = attributes[`iconFrameBgUseGradientPC${suffix}`] ?? attributes[`iconFrameBgUseGradient${suffix}`] ?? attributes.iconFrameBgUseGradient ?? false;
    enabledBreakpoints.forEach((bp) => {
      if (bp !== 'pc') {
        syncAttrs[`iconFrameBgColor${bp.toUpperCase()}${suffix}`] = pcColor;
        syncAttrs[`iconFrameBgColorAlpha${bp.toUpperCase()}${suffix}`] = pcAlpha;
        syncAttrs[`iconFrameBgGradient${bp.toUpperCase()}${suffix}`] = pcGradient;
        syncAttrs[`iconFrameBgUseGradient${bp.toUpperCase()}${suffix}`] = pcUseGradient;
      }
    });
    setAttributes(syncAttrs);
  };

  const renderColorControls = (tabName) => {
    const deviceSuffix = tabName.toUpperCase();
    const colorAttrName = `iconFrameBgColor${deviceSuffix}${suffix}`;
    const alphaAttrName = `iconFrameBgColorAlpha${deviceSuffix}${suffix}`;
    const gradientAttrName = `iconFrameBgGradient${deviceSuffix}${suffix}`;
    const useGradientAttrName = `iconFrameBgUseGradient${deviceSuffix}${suffix}`;

    // フォールバック: デバイス固有 → 汎用 → ベース属性
    const colorValue = attributes[colorAttrName] || attributes[`iconFrameBgColor${suffix}`] || attributes.iconFrameBgColor || "";
    const alphaValue = attributes[alphaAttrName] !== undefined
      ? attributes[alphaAttrName]
      : (attributes[`iconFrameBgColorAlpha${suffix}`] !== undefined
          ? attributes[`iconFrameBgColorAlpha${suffix}`]
          : (attributes.iconFrameBgColorAlpha !== undefined ? attributes.iconFrameBgColorAlpha : 1));
    const gradientValue = attributes[gradientAttrName] || attributes[`iconFrameBgGradient${suffix}`] || attributes.iconFrameBgGradient || "";
    const useGradientValue = attributes[useGradientAttrName] ?? attributes[`iconFrameBgUseGradient${suffix}`] ?? attributes.iconFrameBgUseGradient ?? false;

    const handleColorChangeForDevice = (value) => {
      if (!responsiveEnabled) {
        const updates = {};
        enabledBreakpoints.forEach((bp) => {
          updates[`iconFrameBgColor${bp.toUpperCase()}${suffix}`] = value;
        });
        setAttributes(updates);
      } else {
        setAttributes({ [colorAttrName]: value });
      }
    };

    const handleAlphaChangeForDevice = (value) => {
      if (!responsiveEnabled) {
        const updates = {};
        enabledBreakpoints.forEach((bp) => {
          updates[`iconFrameBgColorAlpha${bp.toUpperCase()}${suffix}`] = value;
        });
        setAttributes(updates);
      } else {
        setAttributes({ [alphaAttrName]: value });
      }
    };

    const handleGradientChangeForDevice = (value) => {
      if (!responsiveEnabled) {
        const updates = {};
        enabledBreakpoints.forEach((bp) => {
          updates[`iconFrameBgGradient${bp.toUpperCase()}${suffix}`] = value;
        });
        setAttributes(updates);
      } else {
        setAttributes({ [gradientAttrName]: value });
      }
    };

    const handleUseGradientChangeForDevice = (value) => {
      if (!responsiveEnabled) {
        const updates = {};
        enabledBreakpoints.forEach((bp) => {
          updates[`iconFrameBgUseGradient${bp.toUpperCase()}${suffix}`] = value;
        });
        setAttributes(updates);
      } else {
        setAttributes({ [useGradientAttrName]: value });
      }
    };

    return (
      <CustomColorPalette
        label={__("Background Color", "zenblocks")}
        color={colorValue}
        alpha={alphaValue}
        gradient={gradientValue}
        useGradient={useGradientValue}
        enableGradient={true}
        enableAlpha={true}
        enableAddButton={true}
        onColorChange={handleColorChangeForDevice}
        onAlphaChange={handleAlphaChangeForDevice}
        onGradientChange={handleGradientChangeForDevice}
        onUseGradientChange={handleUseGradientChangeForDevice}
      />
    );
  };

  return (
    <PanelBodyWithSync
      title={title || __("Color", "zenblocks")}
      initialOpen={initialOpen || panelState}
      onToggle={onTogglePanel}
      onSync={effectiveHoverState ? handleSyncIconFrameColor : undefined}
      className="zenblocks-nested-panel"
      titleClassName="zenblocks-panel-title--no-margin"
      level={3}
      panelType="settings"
      panelName="icon-frame-color"
    >
      <div className="zenblocks-inspector-icon-frame-color">
        <ResponsiveControlV2
          initialOpen={true}
          enableResponsiveToggle={true}
          responsiveEnabled={responsiveEnabled}
          onResponsiveToggle={handleResponsiveToggle}
          attributes={attributes}
          setAttributes={setAttributes}
          syncAttributeName={responsiveAttrName}
        >
          {(tabName) => renderColorControls(tabName)}
        </ResponsiveControlV2>
      </div>
    </PanelBodyWithSync>
  );
};

export default IconFrameColorSettingV4;
