import { RangeControl, SelectControl, Button } 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 getDefaultBackgroundColor = () => ({
  pc: { color: "#000000", gradient: null, useGradient: false, opacity: 0.75, mixBlendMode: "multiply" },
  md: { color: "", gradient: "", useGradient: null, opacity: "", mixBlendMode: "" },
  tb: { color: "", gradient: "", useGradient: null, opacity: "", mixBlendMode: "" },
  sp: { color: "", gradient: "", useGradient: null, opacity: "", mixBlendMode: "" },
});

const BackgroundColorSettingV7 = ({ attributes, setAttributes, title, initialOpen = false, opened, onToggle, onSync, isHoverState = false, supportsHover = true }) => {
  const effectiveHoverState = supportsHover ? isHoverState : false;
  const attrName = effectiveHoverState ? "backgroundColorV2Hover" : "backgroundColorV2";
  const responsiveAttrName = effectiveHoverState ? "useResponsiveBackgroundColorHover" : "useResponsiveBackgroundColor";
  const responsiveEnabled = attributes[responsiveAttrName] !== undefined ? attributes[responsiveAttrName] : false;
  const { activeTab } = useResponsiveTabV2();
  const enabledBreakpoints = getEnabledBreakpoints();

  const bgColorData = attributes[attrName] || getDefaultBackgroundColor();

  // 内部Sync機能: 通常状態の設定をホバー状態にコピー
  const handleSyncColor = () => {
    if (effectiveHoverState) {
      const normalData = attributes.backgroundColorV2 || getDefaultBackgroundColor();
      const normalResponsive = attributes.useResponsiveBackgroundColor || false;
      setAttributes({
        backgroundColorV2Hover: JSON.parse(JSON.stringify(normalData)),
        useResponsiveBackgroundColorHover: normalResponsive,
      });
    } else if (onSync) {
      onSync();
    }
  };

  const mixBlendModeOptions = [
    { label: __("Normal", "zenblocks"), value: "normal" },
    { label: __("Multiply", "zenblocks"), value: "multiply" },
    { label: __("Screen", "zenblocks"), value: "screen" },
    { label: __("Overlay", "zenblocks"), value: "overlay" },
    { label: __("Darken", "zenblocks"), value: "darken" },
    { label: __("Lighten", "zenblocks"), value: "lighten" },
    { label: __("Color Dodge", "zenblocks"), value: "color-dodge" },
    { label: __("Color Burn", "zenblocks"), value: "color-burn" },
    { label: __("Hard Light", "zenblocks"), value: "hard-light" },
    { label: __("Soft Light", "zenblocks"), value: "soft-light" },
    { label: __("Difference", "zenblocks"), value: "difference" },
    { label: __("Exclusion", "zenblocks"), value: "exclusion" },
    { label: __("Hue", "zenblocks"), value: "hue" },
    { label: __("Saturation", "zenblocks"), value: "saturation" },
    { label: __("Color", "zenblocks"), value: "color" },
    { label: __("Luminosity", "zenblocks"), value: "luminosity" },
  ];

  const handleChange = (key, value) => {
    const newData = JSON.parse(JSON.stringify(bgColorData));
    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(bgColorData));
    const emptyBpData = { color: "", gradient: "", useGradient: null, opacity: "", mixBlendMode: "" };
    
    if (value) {
      enabledBreakpoints.forEach((bp) => {
        if (bp !== 'pc') {
          newData[bp] = { ...emptyBpData };
        }
      });
    } else {
      const pcData = newData.pc || getDefaultBackgroundColor().pc;
      enabledBreakpoints.forEach((bp) => {
        newData[bp] = { ...pcData };
      });
    }
    
    setAttributes({ 
      [responsiveAttrName]: value,
      [attrName]: newData 
    });
  };

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

  const renderControls = (tabName) => {
    const tabData = bgColorData[tabName] || getDefaultBackgroundColor().pc;
    const currentColor = tabData.color || "#000000";
    const currentGradient = tabData.gradient || "";
    const useGradient = tabData.useGradient || false;
    const currentOpacity = tabData.opacity !== "" && tabData.opacity !== undefined ? tabData.opacity : 0.75;
    const currentMixBlendMode = tabData.mixBlendMode || "multiply";

    return (
      <>
        <CustomColorPalette
          color={currentColor}
          gradient={currentGradient}
          useGradient={useGradient}
          enableGradient={true}
          enableAlpha={false}
          onColorChange={(value) => handleChange("color", value)}
          onGradientChange={(value) => handleChange("gradient", value)}
          onUseGradientChange={(value) => handleChange("useGradient", value)}
        />

        <RangeControl label={__("Opacity", "zenblocks")} value={currentOpacity} onChange={(value) => handleChange("opacity", value)} min={0} max={1} step={0.01} />

        <SelectControl label={__("Blend Mode", "zenblocks")} value={currentMixBlendMode} options={mixBlendModeOptions} onChange={(value) => handleChange("mixBlendMode", value)} />

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

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

export const getBackgroundColorValue = (attributes, device = "pc", isHover = false) => {
  const attrName = isHover ? "backgroundColorV2Hover" : "backgroundColorV2";
  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) {
      const useGradient = bpData.useGradient;
      if (useGradient && bpData.gradient) {
        return bpData.gradient;
      }
      if (!useGradient && bpData.color && bpData.color !== "") {
        return `linear-gradient(90deg, ${bpData.color} 0%, ${bpData.color} 100%)`;
      }
    }
  }
  return null;
};

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

  const bpData = data[device];
  const useGradient = bpData.useGradient;
  if (useGradient && bpData.gradient) {
    return bpData.gradient;
  }
  if (!useGradient && bpData.color && bpData.color !== "") {
    return `linear-gradient(90deg, ${bpData.color} 0%, ${bpData.color} 100%)`;
  }
  return null;
};

export const getBackgroundColorOpacity = (attributes, device = "pc", isHover = false) => {
  const attrName = isHover ? "backgroundColorV2Hover" : "backgroundColorV2";
  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.opacity !== "" && bpData.opacity !== undefined && bpData.opacity !== null) {
      return bpData.opacity;
    }
  }
  return 0.75;
};

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

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

export const getBackgroundColorMixBlendMode = (attributes, device = "pc", isHover = false) => {
  const attrName = isHover ? "backgroundColorV2Hover" : "backgroundColorV2";
  const data = attributes[attrName];
  if (!data) return "multiply";

  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.mixBlendMode && bpData.mixBlendMode !== "") {
      return bpData.mixBlendMode;
    }
  }
  return "multiply";
};

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

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

export default BackgroundColorSettingV7;
