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 StylingShadowSetting = ({ attributes, setAttributes, title, initialOpen = 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) => {
    const attributeName = `stylingShadow${property}${activeTab.toUpperCase()}`;
    setAttributes({ [attributeName]: value });
  };

  const handleColorChange = (value, tabName) => {
    // クリアボタンが押された場合、transparentを設定
    if (value === undefined || value === null) {
      handleShadowChange("Color", "transparent");
    } else {
      handleShadowChange("Color", value);
    }
  };

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

    return (
      <>
        <ToggleControl
          label={__(`Use drop shadow for ${tabName.toUpperCase()}`, "zenblocks")}
          checked={useShadow}
          onChange={(value) => setAttributes({ [`stylingShadowUse${tabName.toUpperCase()}`]: value })}
        />
        {useShadow && (
          <>
            <div className="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={(color) => handleColorChange(color, tabName)}
                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={__("Horizontal Offset", "zenblocks")}
              value={attributes[`stylingShadowHorizontal${tabName.toUpperCase()}`]}
              onChange={(value) => handleShadowChange("Horizontal", value)}
              min={-50}
              max={50}
              step={1}
            />
            <RangeControl
              label={__("Vertical Offset", "zenblocks")}
              value={attributes[`stylingShadowVertical${tabName.toUpperCase()}`]}
              onChange={(value) => handleShadowChange("Vertical", value)}
              min={-50}
              max={50}
              step={1}
            />
            <RangeControl
              label={__("Blur Radius", "zenblocks")}
              value={attributes[`stylingShadowBlur${tabName.toUpperCase()}`]}
              onChange={(value) => handleShadowChange("Blur", value)}
              min={0}
              max={100}
              step={1}
            />
            <RangeControl
              label={__("Spread Radius", "zenblocks")}
              value={attributes[`stylingShadowSpread${tabName.toUpperCase()}`]}
              onChange={(value) => handleShadowChange("Spread", value)}
              min={-50}
              max={50}
              step={1}
            />
          </>
        )}
      </>
    );
  };

  return (
    <PanelBody title={title} initialOpen={initialOpen}>
      <ResponsiveControl initialOpen={true}>{(tabName) => renderShadowControls(tabName)}</ResponsiveControl>
    </PanelBody>
  );
};

export default StylingShadowSetting;
