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

const getDefaultBackgroundBaseColor = () => ({
  pc: { color: "", alpha: 1, gradient: null, useGradient: false },
  md: { color: "", alpha: "", gradient: "", useGradient: null },
  tb: { color: "", alpha: "", gradient: "", useGradient: null },
  sp: { color: "", alpha: "", gradient: "", useGradient: null },
});

const BackgroundBaseColorSettingV7 = ({ attributes, setAttributes, title, initialOpen = false, opened, onToggle, onSync, isHoverState = false, supportsHover = true }) => {
  const effectiveHoverState = supportsHover ? isHoverState : false;
  const attrName = effectiveHoverState ? "backgroundBaseColorV2Hover" : "backgroundBaseColorV2";
  const responsiveAttrName = effectiveHoverState ? "useResponsiveBackgroundBaseColorHover" : "useResponsiveBackgroundBaseColor";
  const responsiveEnabled = attributes[responsiveAttrName] !== undefined ? attributes[responsiveAttrName] : false;
  const { activeTab } = useResponsiveTabV2();
  const enabledBreakpoints = getEnabledBreakpoints();

  const bgBaseColorData = attributes[attrName] || getDefaultBackgroundBaseColor();

  // 内部Sync機能: 通常状態の設定をホバー状態にコピー
  const handleSyncBaseColor = () => {
    if (effectiveHoverState) {
      const normalData = attributes.backgroundBaseColorV2 || getDefaultBackgroundBaseColor();
      const normalResponsive = attributes.useResponsiveBackgroundBaseColor || false;
      setAttributes({
        backgroundBaseColorV2Hover: JSON.parse(JSON.stringify(normalData)),
        useResponsiveBackgroundBaseColorHover: normalResponsive,
      });
    } else if (onSync) {
      onSync();
    }
  };

  const handleChange = (key, value) => {
    const newData = JSON.parse(JSON.stringify(bgBaseColorData));
    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(bgBaseColorData));
    const emptyBpData = { color: "", alpha: "", gradient: "", useGradient: null, opacity: "", mixBlendMode: "" };

    if (value) {
      // レスポンシブON: PCの値をMD/TB/SPにコピー（同期）
      const pcData = newData.pc || getDefaultBackgroundBaseColor().pc;
      enabledBreakpoints.forEach((bp) => {
        if (bp !== 'pc') {
          newData[bp] = { ...pcData };
        }
      });
    } else {
      // レスポンシブOFF: MD/TB/SPをデフォルト（空）にリセット（PCから継承）
      enabledBreakpoints.forEach((bp) => {
        if (bp !== 'pc') {
          newData[bp] = { ...emptyBpData };
        }
      });
    }

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

  const resetBackgroundBaseColor = () => {
    const defaultData = getDefaultBackgroundBaseColor();
    if (responsiveEnabled) {
      const newData = JSON.parse(JSON.stringify(bgBaseColorData));
      newData[activeTab] = { ...defaultData.pc };
      setAttributes({ [attrName]: newData });
    } else {
      setAttributes({ [attrName]: defaultData });
    }
  };

  const renderControls = (tabName) => {
    const tabData = bgBaseColorData[tabName] || getDefaultBackgroundBaseColor().pc;
    const currentColor = tabData.color || "";
    const currentAlpha = tabData.alpha !== "" && tabData.alpha !== undefined ? tabData.alpha : 1;
    const useGradient = tabData.useGradient || false;
    const gradient = tabData.gradient || "";

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

        {useGradient && (
          <Notice status="warning" isDismissible={false} className="zenblocks-gradient-notice">
            {__("グラデーションにはトランジション効果が適用されません。スムーズなトランジションにはオーバーレイをご利用ください。", "zenblocks")}
          </Notice>
        )}

        <Button variant="secondary" onClick={resetBackgroundBaseColor} style={{ marginTop: "10px" }}>
          {__("Reset", "zenblocks")}
        </Button>
      </>
    );
  };

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

export const getBackgroundBaseColorValue = (attributes, device = "pc", isHover = false) => {
  const attrName = isHover ? "backgroundBaseColorV2Hover" : "backgroundBaseColorV2";
  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 !== "") {
      return bpData.color;
    }
  }
  return null;
};

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

  const bpData = data[device];
  if (bpData.color && bpData.color !== "") {
    return bpData.color;
  }
  return null;
};

export default BackgroundBaseColorSettingV7;
