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

const getDefaultInnerShadow = () => ({
  pc: { use: false, horizontal: 0, vertical: 0, blur: 10, spread: 0, color: "#ffffff", colorAlpha: 1 },
  md: { use: "", horizontal: "", vertical: "", blur: "", spread: "", color: "", colorAlpha: "" },
  tb: { use: "", horizontal: "", vertical: "", blur: "", spread: "", color: "", colorAlpha: "" },
  sp: { use: "", horizontal: "", vertical: "", blur: "", spread: "", color: "", colorAlpha: "" },
});

const StylingInnerShadowSettingV5 = ({ attributes, setAttributes, title, initialOpen = false, opened, onToggle, onSync, isHoverState = false, supportsHover = true, isPro = false }) => {
  const effectiveHoverState = supportsHover ? isHoverState : false;
  const v2Key = effectiveHoverState ? "innerShadowV2Hover" : "innerShadowV2";
  const enabledAttrName = effectiveHoverState ? "innerShadowEnabledHover" : "innerShadowEnabled";
  const responsiveAttrName = effectiveHoverState ? "useResponsiveInnerShadowHover" : "useResponsiveInnerShadow";
  const responsiveEnabled = attributes[responsiveAttrName] !== undefined ? attributes[responsiveAttrName] : false;
  const innerShadowEnabled = attributes[enabledAttrName] !== undefined ? attributes[enabledAttrName] : false;
  const { activeTab } = useResponsiveTabV2();
  const enabledBreakpoints = getEnabledBreakpoints();

  const innerShadowData = attributes[v2Key] || getDefaultInnerShadow();

  // 内部Sync機能: 通常状態の設定をホバー状態にコピー
  const handleSyncInnerShadow = () => {
    if (effectiveHoverState) {
      const normalData = attributes.innerShadowV2 || getDefaultInnerShadow();
      const normalEnabled = attributes.innerShadowEnabled !== undefined ? attributes.innerShadowEnabled : false;
      const normalResponsive = attributes.useResponsiveInnerShadow || false;
      setAttributes({
        innerShadowV2Hover: JSON.parse(JSON.stringify(normalData)),
        innerShadowEnabledHover: normalEnabled,
        useResponsiveInnerShadowHover: normalResponsive,
      });
    } else if (onSync) {
      onSync();
    }
  };

  const handleInnerShadowChange = (property, value) => {
    const newInnerShadow = JSON.parse(JSON.stringify(innerShadowData));
    if (!responsiveEnabled) {
      enabledBreakpoints.forEach((bp) => {
        newInnerShadow[bp][property] = value;
        if (newInnerShadow[bp].use === "" || newInnerShadow[bp].use === undefined) {
          newInnerShadow[bp].use = true;
        }
      });
    } else {
      newInnerShadow[activeTab][property] = value;
      if (newInnerShadow[activeTab].use === "" || newInnerShadow[activeTab].use === undefined) {
        newInnerShadow[activeTab].use = true;
      }
    }
    setAttributes({ [v2Key]: newInnerShadow });
  };

  const handleColorChange = (value) => {
    handleInnerShadowChange("color", value === undefined || value === null ? "transparent" : value);
  };

  const handleColorAlphaChange = (value) => {
    handleInnerShadowChange("colorAlpha", value);
  };

  const handleInnerShadowEnabledToggle = (value) => {
    setAttributes({ [enabledAttrName]: value });
    const newInnerShadow = JSON.parse(JSON.stringify(innerShadowData));
    if (value) {
      enabledBreakpoints.forEach((bp, index) => {
        if (index === 0) {
          newInnerShadow[bp] = { use: true, horizontal: 0, vertical: 0, blur: 10, spread: 0, color: "#ffffff", colorAlpha: 1 };
        } else {
          newInnerShadow[bp] = { use: "", horizontal: "", vertical: "", blur: "", spread: "", color: "", colorAlpha: "" };
        }
      });
    } else {
      enabledBreakpoints.forEach((bp, index) => {
        if (index === 0) {
          newInnerShadow[bp] = { use: false, horizontal: 0, vertical: 0, blur: 10, spread: 0, color: "#ffffff", colorAlpha: 1 };
        } else {
          newInnerShadow[bp] = { use: "", horizontal: "", vertical: "", blur: "", spread: "", color: "", colorAlpha: "" };
        }
      });
    }
    setAttributes({ [v2Key]: newInnerShadow });
  };

  const handleResponsiveToggle = (value) => {
    const newInnerShadow = JSON.parse(JSON.stringify(innerShadowData));
    const pcData = newInnerShadow.pc;
    enabledBreakpoints.forEach((bp) => {
      if (bp !== "pc") {
        newInnerShadow[bp] = { ...pcData };
      }
    });
    setAttributes({ [v2Key]: newInnerShadow, [responsiveAttrName]: value });
  };

  const renderInnerShadowControls = (tabName) => {
    const tabData = innerShadowData[tabName] || getDefaultInnerShadow().pc;
    const colorValue = tabData.color;
    const colorAlphaValue = tabData.colorAlpha !== "" && tabData.colorAlpha !== undefined ? tabData.colorAlpha : 1;

    return (
      <>
        <CustomColorPalette
          color={colorValue}
          alpha={colorAlphaValue}
          enableGradient={false}
          enableAlpha={true}
          onColorChange={handleColorChange}
          onAlphaChange={handleColorAlphaChange}
          label={__("Color", "zenblocks")}
        />

        <RangeControl
          label={__("Blur", "zenblocks")}
          value={tabData.blur === "" ? 10 : tabData.blur}
          onChange={(value) => handleInnerShadowChange("blur", value)}
          min={0}
          max={100}
          step={1}
          className="zenblocks-inspector-styling-inner-shadow__blur-control"
        />
        <RangeControl
          label={__("Horizontal", "zenblocks")}
          value={tabData.horizontal === "" ? 0 : tabData.horizontal}
          onChange={(value) => handleInnerShadowChange("horizontal", value)}
          min={-50}
          max={50}
          step={1}
          className="zenblocks-inspector-styling-inner-shadow__horizontal-control"
        />
        <RangeControl
          label={__("Vertical", "zenblocks")}
          value={tabData.vertical === "" ? 0 : tabData.vertical}
          onChange={(value) => handleInnerShadowChange("vertical", value)}
          min={-50}
          max={50}
          step={1}
          className="zenblocks-inspector-styling-inner-shadow__vertical-control"
        />
        <RangeControl
          label={__("Spread", "zenblocks")}
          value={tabData.spread === "" ? 0 : tabData.spread}
          onChange={(value) => handleInnerShadowChange("spread", value)}
          min={-50}
          max={50}
          step={1}
          className="zenblocks-inspector-styling-inner-shadow__spread-control"
        />
      </>
    );
  };

  const content = (
    <div className="zenblocks-inspector-styling-inner-shadow">
      <StyledToggle label={__("Inner Shadow", "zenblocks")} checked={innerShadowEnabled} onChange={handleInnerShadowEnabledToggle} />
      {innerShadowEnabled && (
        <ResponsiveControlV2
          initialOpen={true}
          enableResponsiveToggle={true}
          responsiveEnabled={responsiveEnabled}
          onResponsiveToggle={handleResponsiveToggle}
          attributes={attributes}
          setAttributes={setAttributes}
          syncAttributeName={responsiveAttrName}
        >
          {(tabName) => renderInnerShadowControls(tabName)}
        </ResponsiveControlV2>
      )}
    </div>
  );

  return (
    <PanelBodyWithSync
      title={title}
      initialOpen={initialOpen}
      opened={opened}
      onToggle={onToggle}
      onSync={effectiveHoverState ? handleSyncInnerShadow : undefined}
      className="zenblocks-nested-panel"
      level={2}
      panelType="settings"
      panelName="styling-inner-shadow"
    >
      {isPro ? <ProFeatureOverlay featureName="Inner Shadow">{content}</ProFeatureOverlay> : content}
    </PanelBodyWithSync>
  );
};

export const getInnerShadowValue = (attributes, device = "pc", isHoverState = false) => {
  const v2Key = isHoverState ? "innerShadowV2Hover" : "innerShadowV2";
  const innerShadowData = attributes[v2Key];
  if (!innerShadowData) return "none";

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

  for (let i = currentIndex; i >= 0; i--) {
    const bp = enabledBreakpoints[i];
    const bpData = innerShadowData[bp];
    if (bpData && (bpData.use === true || bpData.use === "true")) {
      const h = bpData.horizontal || 0;
      const v = bpData.vertical || 4;
      const blur = bpData.blur || 8;
      const spread = bpData.spread || 0;
      const color = bpData.color || "#000000";
      const colorAlpha = bpData.colorAlpha !== "" && bpData.colorAlpha !== undefined ? bpData.colorAlpha : (bpData.opacity !== undefined ? bpData.opacity / 100 : 1);
      const rgba = hexToRgba(color, colorAlpha);
      return `inset ${h}px ${v}px ${blur}px ${spread}px ${rgba}`;
    }
  }

  return "none";
};

export default StylingInnerShadowSettingV5;
