import React from "react";
import { __ } from "@wordpress/i18n";
import { PanelBody, RangeControl, ColorPalette, ToggleControl } from "@wordpress/components";
import { useSelect } from "@wordpress/data";
import { store as blockEditorStore } from "@wordpress/block-editor";
import ResponsiveControl from "../../ResponsiveControl";
import { useResponsiveTab } from "../../ResponsiveTabContext";

const StylingShadowSettingV3 = ({ attributes, setAttributes, title, initialOpen = false }) => {
  const responsiveEnabled = attributes.responsiveStylingShadow !== undefined ? attributes.responsiveStylingShadow : false;
  const { activeTab } = useResponsiveTab();

  // テーマカラーを取得
  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) {
      // レスポンシブOFF時: PCとSP両方を更新
      setAttributes({
        [`stylingShadow${property}PC`]: value,
        [`stylingShadow${property}SP`]: value,
      });
    } else {
      // レスポンシブON時: 現在のタブのみ更新
      const attributeName = `stylingShadow${property}${activeTab.toUpperCase()}`;
      setAttributes({ [attributeName]: value });
    }
  };

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

  const handleUseShadowToggle = (value) => {
    if (!responsiveEnabled) {
      // レスポンシブOFF時: PCとSP両方を更新
      setAttributes({
        stylingShadowUsePC: value,
        stylingShadowUseSP: value,
      });
    } else {
      // レスポンシブON時: 現在のタブのみ更新
      setAttributes({ [`stylingShadowUse${activeTab.toUpperCase()}`]: value });
    }
  };

  const handleResponsiveToggle = (value) => {
    setAttributes({ responsiveStylingShadow: value });

    if (!value) {
      // レスポンシブOFFにする時、PCの値をSPに同期
      setAttributes({
        stylingShadowUseSP: attributes.stylingShadowUsePC,
        stylingShadowHorizontalSP: attributes.stylingShadowHorizontalPC,
        stylingShadowVerticalSP: attributes.stylingShadowVerticalPC,
        stylingShadowBlurSP: attributes.stylingShadowBlurPC,
        stylingShadowSpreadSP: attributes.stylingShadowSpreadPC,
        stylingShadowColorSP: attributes.stylingShadowColorPC,
      });
    }
  };

  const renderShadowControls = (tabName) => {
    // レスポンシブOFF時はPCの値を参照、ON時は各タブの値を参照
    const useShadow = !responsiveEnabled ? attributes.stylingShadowUsePC : attributes[`stylingShadowUse${tabName.toUpperCase()}`];
    const colorValue = attributes[`stylingShadowColor${tabName.toUpperCase()}`];

    return (
      <div className="zenblocks-inspector-styling-shadow">
        <ToggleControl
          label={__(`Use drop shadow for ${tabName.toUpperCase()}`, "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${tabName.toUpperCase()}`]}
              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${tabName.toUpperCase()}`]}
              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${tabName.toUpperCase()}`]}
              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${tabName.toUpperCase()}`]}
              onChange={(value) => handleShadowChange("Spread", value)}
              min={-50}
              max={50}
              step={1}
              className="zenblocks-inspector-styling-shadow__spread-control"
            />
          </>
        )}
      </div>
    );
  };

  return (
    <PanelBody title={title} initialOpen={initialOpen}>
      <ResponsiveControl
        initialOpen={true}
        enableResponsiveToggle={true}
        responsiveEnabled={responsiveEnabled}
        onResponsiveToggle={handleResponsiveToggle}
        attributes={attributes}
        setAttributes={setAttributes}
        syncAttributeName="responsiveStylingShadow"
      >
        {(tabName) => renderShadowControls(tabName)}
      </ResponsiveControl>
    </PanelBody>
  );
};

export default StylingShadowSettingV3;
