import React from "react";
import { __ } from "@wordpress/i18n";
import { RangeControl, ColorPalette, ToggleControl } from "@wordpress/components";
import { useSelect } from "@wordpress/data";
import { store as blockEditorStore } from "@wordpress/block-editor";
import ResponsiveControlV2 from "../../ResponsiveControlV2";
import { useResponsiveTabV2 } from "../../ResponsiveTabContextV2";
import PanelBodyWithSync from "../../PanelBodyWithSync";
import ProFeatureOverlay from "../../ProFeatureOverlay";
import { getEnabledBreakpoints } from "../../../../../core/breakpoints";

const StylingShadowSettingV6 = ({ attributes, setAttributes, title, initialOpen = false, onSync, isHoverState = false, supportsHover = true, isPro = false }) => {
  const effectiveHoverState = supportsHover ? isHoverState : false;
  const hoverSuffix = effectiveHoverState ? 'Hover' : '';
  const responsiveAttrName = effectiveHoverState ? 'responsiveStylingShadowHover' : 'responsiveStylingShadow';
  const responsiveEnabled = attributes[responsiveAttrName] !== undefined ? attributes[responsiveAttrName] : false;
  const { activeTab } = useResponsiveTabV2();
  const enabledBreakpoints = getEnabledBreakpoints();

  const themeColors = useSelect((select) => {
    const settings = select(blockEditorStore).getSettings();
    return settings.colors || [];
  }, []);

  const customColors = [
    { name: __("Transparent", "zenblocks"), color: "transparent" },
    { name: __("Black", "zenblocks"), color: "#000000" },
    { name: __("White", "zenblocks"), color: "#ffffff" },
    ...themeColors.map((color) => ({
      name: color.name,
      color: color.color,
    })),
  ];

  const handleShadowChange = (property, value) => {
    if (!responsiveEnabled) {
      const attrs = {};
      enabledBreakpoints.forEach(bp => {
        attrs[`stylingShadow${property}${bp.toUpperCase()}${hoverSuffix}`] = value;
      });
      setAttributes(attrs);
    } else {
      const deviceSuffix = activeTab.toUpperCase();
      const attributeName = `stylingShadow${property}${deviceSuffix}${hoverSuffix}`;
      setAttributes({ [attributeName]: value });
    }
  };

  const handleColorChange = (value) => {
    if (value === undefined || value === null) {
      handleShadowChange("Color", "transparent");
    } else {
      handleShadowChange("Color", value);
    }
  };

  const handleUseShadowToggle = (value) => {
    if (!responsiveEnabled) {
      const attrs = {};
      enabledBreakpoints.forEach(bp => {
        attrs[`stylingShadowUse${bp.toUpperCase()}${hoverSuffix}`] = value;
      });
      setAttributes(attrs);
    } else {
      const deviceSuffix = activeTab.toUpperCase();
      setAttributes({ [`stylingShadowUse${deviceSuffix}${hoverSuffix}`]: value });
    }
  };

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

    const syncAttrs = {};
    enabledBreakpoints.slice(1).forEach(bp => {
      syncAttrs[`stylingShadowUse${bp.toUpperCase()}${hoverSuffix}`] = attributes[`stylingShadowUsePC${hoverSuffix}`];
      syncAttrs[`stylingShadowHorizontal${bp.toUpperCase()}${hoverSuffix}`] = attributes[`stylingShadowHorizontalPC${hoverSuffix}`];
      syncAttrs[`stylingShadowVertical${bp.toUpperCase()}${hoverSuffix}`] = attributes[`stylingShadowVerticalPC${hoverSuffix}`];
      syncAttrs[`stylingShadowBlur${bp.toUpperCase()}${hoverSuffix}`] = attributes[`stylingShadowBlurPC${hoverSuffix}`];
      syncAttrs[`stylingShadowSpread${bp.toUpperCase()}${hoverSuffix}`] = attributes[`stylingShadowSpreadPC${hoverSuffix}`];
      syncAttrs[`stylingShadowColor${bp.toUpperCase()}${hoverSuffix}`] = attributes[`stylingShadowColorPC${hoverSuffix}`];
    });
    setAttributes(syncAttrs);
  };

  const renderShadowControls = (tabName) => {
    const deviceSuffix = tabName.toUpperCase();
    const useShadow = attributes[`stylingShadowUse${deviceSuffix}${hoverSuffix}`];
    const colorValue = attributes[`stylingShadowColor${deviceSuffix}${hoverSuffix}`];

    return (
      <div className="zenblocks-inspector-styling-shadow">
        <ToggleControl
          label={__(`Use drop shadow for ${deviceSuffix}`, "zenblocks")}
          checked={useShadow}
          onChange={handleUseShadowToggle}
          className="zenblocks-inspector-styling-shadow__use-toggle"
        />
        {useShadow && (
          <>
            <div className="zenblocks-inspector-styling-shadow__color-control" style={{ marginBottom: "10px" }}>
              <label style={{ display: "block", marginBottom: "8px", fontSize: "12px", fontWeight: "normal" }}>{__("Color", "zenblocks")}</label>
              <ColorPalette colors={customColors} value={colorValue === "transparent" ? undefined : colorValue} onChange={handleColorChange} disableCustomColors={false} clearable={true} />
              {colorValue === "transparent" && (
                <div
                  style={{
                    marginTop: "8px",
                    padding: "8px",
                    backgroundColor: "#f0f0f0",
                    borderRadius: "4px",
                    fontSize: "12px",
                    color: "#666",
                  }}
                >
                  {__("Current setting: Transparent", "zenblocks")}
                </div>
              )}
            </div>
            <RangeControl
              label={__("Blur Radius", "zenblocks")}
              value={attributes[`stylingShadowBlur${deviceSuffix}${hoverSuffix}`]}
              onChange={(value) => handleShadowChange("Blur", value)}
              min={0}
              max={100}
              step={1}
              className="zenblocks-inspector-styling-shadow__blur-control"
            />
            <RangeControl
              label={__("Horizontal Offset", "zenblocks")}
              value={attributes[`stylingShadowHorizontal${deviceSuffix}${hoverSuffix}`]}
              onChange={(value) => handleShadowChange("Horizontal", value)}
              min={-50}
              max={50}
              step={1}
              className="zenblocks-inspector-styling-shadow__horizontal-control"
            />
            <RangeControl
              label={__("Vertical Offset", "zenblocks")}
              value={attributes[`stylingShadowVertical${deviceSuffix}${hoverSuffix}`]}
              onChange={(value) => handleShadowChange("Vertical", value)}
              min={-50}
              max={50}
              step={1}
              className="zenblocks-inspector-styling-shadow__vertical-control"
            />
            <RangeControl
              label={__("Spread Radius", "zenblocks")}
              value={attributes[`stylingShadowSpread${deviceSuffix}${hoverSuffix}`]}
              onChange={(value) => handleShadowChange("Spread", value)}
              min={-50}
              max={50}
              step={1}
              className="zenblocks-inspector-styling-shadow__spread-control"
            />
          </>
        )}
      </div>
    );
  };

  const content = (
    <ResponsiveControlV2
      initialOpen={true}
      enableResponsiveToggle={true}
      responsiveEnabled={responsiveEnabled}
      onResponsiveToggle={handleResponsiveToggle}
      attributes={attributes}
      setAttributes={setAttributes}
      syncAttributeName={responsiveAttrName}
    >
      {(tabName) => renderShadowControls(tabName)}
    </ResponsiveControlV2>
  );

  return (
    <PanelBodyWithSync title={title} initialOpen={initialOpen} onSync={onSync} className="zenblocks-nested-panel">
      {isPro ? <ProFeatureOverlay featureName="シャドウ設定">{content}</ProFeatureOverlay> : content}
    </PanelBodyWithSync>
  );
};

export default StylingShadowSettingV6;
