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 getDefaultShadow = () => ({
  pc: { use: false, horizontal: 0, vertical: 4, blur: 8, spread: 0, color: "#000000", colorAlpha: 0.2, inset: false },
  md: { use: "", horizontal: "", vertical: "", blur: "", spread: "", color: "", colorAlpha: "", inset: "" },
  tb: { use: "", horizontal: "", vertical: "", blur: "", spread: "", color: "", colorAlpha: "", inset: "" },
  sp: { use: "", horizontal: "", vertical: "", blur: "", spread: "", color: "", colorAlpha: "", inset: "" }
});

const StylingShadowSettingV5 = ({ attributes, setAttributes, title, initialOpen = false, opened, onToggle, onSync, isHoverState = false, supportsHover = true, isPro = false }) => {
  const effectiveHoverState = supportsHover ? isHoverState : false;
  const v2Key = effectiveHoverState ? 'shadowV2Hover' : 'shadowV2';
  const enabledAttrName = effectiveHoverState ? 'shadowEnabledHover' : 'shadowEnabled';
  const responsiveAttrName = effectiveHoverState ? 'useResponsiveShadowHover' : 'useResponsiveShadow';
  const responsiveEnabled = attributes[responsiveAttrName] !== undefined ? attributes[responsiveAttrName] : false;
  const shadowEnabled = attributes[enabledAttrName] !== undefined ? attributes[enabledAttrName] : false;
  const { activeTab } = useResponsiveTabV2();
  const enabledBreakpoints = getEnabledBreakpoints();

  const shadowData = attributes[v2Key] || getDefaultShadow();

  // 内部Sync機能: 通常状態の設定をホバー状態にコピー
  const handleSyncShadow = () => {
    if (effectiveHoverState) {
      const normalData = attributes.shadowV2 || getDefaultShadow();
      const normalEnabled = attributes.shadowEnabled !== undefined ? attributes.shadowEnabled : false;
      const normalResponsive = attributes.useResponsiveShadow || false;
      setAttributes({
        shadowV2Hover: JSON.parse(JSON.stringify(normalData)),
        shadowEnabledHover: normalEnabled,
        useResponsiveShadowHover: normalResponsive,
      });
    } else if (onSync) {
      onSync();
    }
  };

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

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

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

  const handleShadowEnabledToggle = (value) => {
    setAttributes({ [enabledAttrName]: value });
    const newShadow = JSON.parse(JSON.stringify(shadowData));
    if (value) {
      enabledBreakpoints.forEach((bp, index) => {
        if (index === 0) {
          newShadow[bp] = { use: true, horizontal: 0, vertical: 4, blur: 8, spread: 0, color: "#000000", colorAlpha: 0.2, inset: false };
        } else {
          newShadow[bp] = { use: "", horizontal: "", vertical: "", blur: "", spread: "", color: "", colorAlpha: "", inset: "" };
        }
      });
    } else {
      enabledBreakpoints.forEach((bp, index) => {
        if (index === 0) {
          newShadow[bp] = { use: false, horizontal: 0, vertical: 4, blur: 8, spread: 0, color: "#000000", colorAlpha: 0.2, inset: false };
        } else {
          newShadow[bp] = { use: "", horizontal: "", vertical: "", blur: "", spread: "", color: "", colorAlpha: "", inset: "" };
        }
      });
    }
    setAttributes({ [v2Key]: newShadow });
  };

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

  const renderShadowControls = (tabName) => {
    const tabData = shadowData[tabName] || getDefaultShadow().pc;
    const colorValue = tabData.color;
    const colorAlphaValue = tabData.colorAlpha !== "" && tabData.colorAlpha !== undefined ? tabData.colorAlpha : (tabData.opacity !== undefined && tabData.opacity !== "" ? tabData.opacity / 100 : 0.2);

    return (
      <>
        <CustomColorPalette
          color={colorValue}
          alpha={colorAlphaValue}
          enableGradient={false}
          enableAlpha={true}
          onColorChange={handleColorChange}
          onAlphaChange={handleColorAlphaChange}
          label={__("Color", "zenblocks")}
        />
        <RangeControl
          label={__("Blur", "zenblocks")}
          value={tabData.blur === "" ? 8 : tabData.blur}
          onChange={(value) => handleShadowChange("blur", value)}
          min={0}
          max={100}
          step={1}
          className="zenblocks-inspector-styling-shadow__blur-control"
        />
        <RangeControl
          label={__("Horizontal", "zenblocks")}
          value={tabData.horizontal === "" ? 0 : tabData.horizontal}
          onChange={(value) => handleShadowChange("horizontal", value)}
          min={-50}
          max={50}
          step={1}
          className="zenblocks-inspector-styling-shadow__horizontal-control"
        />
        <RangeControl
          label={__("Vertical", "zenblocks")}
          value={tabData.vertical === "" ? 4 : tabData.vertical}
          onChange={(value) => handleShadowChange("vertical", value)}
          min={-50}
          max={50}
          step={1}
          className="zenblocks-inspector-styling-shadow__vertical-control"
        />
        <RangeControl
          label={__("Spread", "zenblocks")}
          value={tabData.spread === "" ? 0 : tabData.spread}
          onChange={(value) => handleShadowChange("spread", value)}
          min={-50}
          max={50}
          step={1}
          className="zenblocks-inspector-styling-shadow__spread-control"
        />
      </>
    );
  };

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

  return (
    <PanelBodyWithSync title={title} initialOpen={initialOpen} opened={opened} onToggle={onToggle} onSync={effectiveHoverState ? handleSyncShadow : undefined} className="zenblocks-nested-panel" level={2} panelType="settings" panelName="styling-shadow">
      {isPro ? <ProFeatureOverlay featureName="シャドウ設定">{content}</ProFeatureOverlay> : content}
    </PanelBodyWithSync>
  );
};

export const getShadowValue = (attributes, device = "pc", isHoverState = false) => {
  const v2Key = isHoverState ? 'shadowV2Hover' : 'shadowV2';
  const shadowData = attributes[v2Key];
  if (!shadowData) return "none";

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

  for (let i = currentIndex; i >= 0; i--) {
    const bp = enabledBreakpoints[i];
    const bpData = shadowData[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 : 0.2);
      const inset = bpData.inset ? "inset " : "";
      const rgba = hexToRgba(color, colorAlpha);
      return `${inset}${h}px ${v}px ${blur}px ${spread}px ${rgba}`;
    }
  }

  return "none";
};

export default StylingShadowSettingV5;
