import React from "react";
import { __ } from "@wordpress/i18n";
import { RangeControl, SelectControl } from "@wordpress/components";
import ResponsiveControlV2 from "../../ResponsiveControlV2";
import { useResponsiveTabV2 } from "../../ResponsiveTabContextV2";
import PanelBodyWithSync from "../../PanelBodyWithSync";
import ProFeatureOverlay from "../../ProFeatureOverlay";
import { getEnabledBreakpoints } from "../../../../../core/breakpoints";

const getDefaultOpacity = () => ({
  pc: { value: 100, mixBlendMode: "normal" },
  md: { value: "", mixBlendMode: "" },
  tb: { value: "", mixBlendMode: "" },
  sp: { value: "", mixBlendMode: "" }
});

const StylingOpacitySettingV5 = ({ attributes, setAttributes, title, initialOpen = false, opened, onToggle, onSync, isHoverState = false, supportsHover = true, isPro = false }) => {
  const effectiveHoverState = supportsHover ? isHoverState : false;
  const v2Key = effectiveHoverState ? "opacityV2Hover" : "opacityV2";
  const responsiveAttrName = effectiveHoverState ? "useResponsiveOpacityHover" : "useResponsiveOpacity";
  const responsiveEnabled = attributes[responsiveAttrName] !== undefined ? attributes[responsiveAttrName] : false;
  const { activeTab } = useResponsiveTabV2();
  const enabledBreakpoints = getEnabledBreakpoints();

  const opacityData = attributes[v2Key] || getDefaultOpacity();

  // 内部Sync機能: 通常状態の設定をホバー状態にコピー
  const handleSyncOpacity = () => {
    if (effectiveHoverState) {
      const normalData = attributes.opacityV2 || getDefaultOpacity();
      const normalResponsive = attributes.useResponsiveOpacity || false;
      setAttributes({
        opacityV2Hover: JSON.parse(JSON.stringify(normalData)),
        useResponsiveOpacityHover: normalResponsive,
      });
    } else if (onSync) {
      onSync();
    }
  };

  const handleOpacityChange = (value) => {
    const newOpacity = JSON.parse(JSON.stringify(opacityData));
    if (!responsiveEnabled) {
      enabledBreakpoints.forEach((bp) => {
        newOpacity[bp].value = value;
      });
    } else {
      newOpacity[activeTab].value = value;
    }
    setAttributes({ [v2Key]: newOpacity });
  };

  const handleMixBlendModeChange = (value) => {
    const newOpacity = JSON.parse(JSON.stringify(opacityData));
    if (!responsiveEnabled) {
      enabledBreakpoints.forEach((bp) => {
        newOpacity[bp].mixBlendMode = value;
      });
    } else {
      newOpacity[activeTab].mixBlendMode = value;
    }
    setAttributes({ [v2Key]: newOpacity });
  };

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

    const newOpacity = JSON.parse(JSON.stringify(opacityData));
    const pcData = newOpacity.pc;
    enabledBreakpoints.forEach((bp) => {
      if (bp !== 'pc') {
        newOpacity[bp] = { ...pcData };
      }
    });
    setAttributes({ [v2Key]: newOpacity });
  };

  const mixBlendModes = [
    { 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 renderOpacityControls = (tabName) => {
    const tabData = opacityData[tabName] || getDefaultOpacity().pc;
    const opacityValue = tabData.value === "" ? 100 : tabData.value;
    const mixBlendModeValue = tabData.mixBlendMode || "normal";

    return (
      <>
        <RangeControl
          label={__("Opacity", "zenblocks")}
          value={opacityValue / 100}
          onChange={(value) => handleOpacityChange(Math.round(value * 100))}
          min={0}
          max={1}
          step={0.01}
          className="zenblocks-inspector-styling-opacity__opacity-control"
        />
        <SelectControl
          label={__("Mix Blend Mode", "zenblocks")}
          value={mixBlendModeValue}
          options={mixBlendModes}
          onChange={handleMixBlendModeChange}
          className="zenblocks-inspector-styling-opacity__blend-mode-select"
        />
      </>
    );
  };

  const content = (
    <div className="zenblocks-inspector-styling-opacity">
      <ResponsiveControlV2
      initialOpen={true}
      enableResponsiveToggle={true}
      responsiveEnabled={responsiveEnabled}
      onResponsiveToggle={handleResponsiveToggle}
      attributes={attributes}
      setAttributes={setAttributes}
      syncAttributeName={responsiveAttrName}
    >
      {(tabName) => renderOpacityControls(tabName)}
      </ResponsiveControlV2>
    </div>
  );

  return (
    <PanelBodyWithSync title={title} initialOpen={initialOpen} opened={opened} onToggle={onToggle} onSync={effectiveHoverState ? handleSyncOpacity : undefined} className="zenblocks-nested-panel" level={2} panelType="settings" panelName="styling-opacity">
      {isPro ? <ProFeatureOverlay featureName="透明設定">{content}</ProFeatureOverlay> : content}
    </PanelBodyWithSync>
  );
};

export const getOpacityValue = (attributes, device = "pc", isHoverState = false) => {
  const v2Key = isHoverState ? "opacityV2Hover" : "opacityV2";
  const opacityData = attributes[v2Key];
  if (!opacityData) return 100;

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

  for (let i = currentIndex; i >= 0; i--) {
    const bp = enabledBreakpoints[i];
    const bpData = opacityData[bp];
    if (bpData && bpData.value !== "" && bpData.value !== undefined && bpData.value !== null) {
      return bpData.value;
    }
  }

  return 100;
};

export const getMixBlendModeValue = (attributes, device = "pc", isHoverState = false) => {
  const v2Key = isHoverState ? "opacityV2Hover" : "opacityV2";
  const opacityData = attributes[v2Key];
  if (!opacityData) return "normal";

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

  for (let i = currentIndex; i >= 0; i--) {
    const bp = enabledBreakpoints[i];
    const bpData = opacityData[bp];
    if (bpData && bpData.mixBlendMode && bpData.mixBlendMode !== "") {
      return bpData.mixBlendMode;
    }
  }

  return "normal";
};

export default StylingOpacitySettingV5;
