import React from "react";
import { __ } from "@wordpress/i18n";
import { PanelBody, RangeControl, SelectControl, ColorPalette } 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 StylingBorderSetting = ({ 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 handleBorderChange = (property, value) => {
    const attributeName = `stylingBorder${property}${activeTab.toUpperCase()}`;
    setAttributes({ [attributeName]: value });
  };

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

  const borderStyles = [
    { label: __("None", "zenblocks"), value: "none" },
    { label: __("Solid", "zenblocks"), value: "solid" },
    { label: __("Dashed", "zenblocks"), value: "dashed" },
    { label: __("Dotted", "zenblocks"), value: "dotted" },
  ];

  const renderBorderControls = (tabName) => {
    const colorValue = attributes[`stylingBorderColor${tabName.toUpperCase()}`];

    return (
      <>
        <RangeControl
          label={__("Width", "zenblocks")}
          value={attributes[`stylingBorderWidth${tabName.toUpperCase()}`]}
          onChange={(value) => handleBorderChange("Width", value)}
          min={0}
          max={100}
          step={1}
        />
        <SelectControl
          label={__("Style", "zenblocks")}
          value={attributes[`stylingBorderStyle${tabName.toUpperCase()}`]}
          options={borderStyles}
          onChange={(value) => handleBorderChange("Style", value)}
        />
        <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>
      </>
    );
  };

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

export default StylingBorderSetting;
