/**
 * CustomColorPalette
 *
 * 共通カラーパレットコンポーネント
 * - テーマカラー/カスタムカラーの選択
 * - alpha値（rgba）の設定
 * - グラデーション切り替え（オプション）
 */

import { __ } from "@wordpress/i18n";
import { ColorPalette, GradientPicker, RangeControl } from "@wordpress/components";
import { useSettings } from "@wordpress/block-editor";

/**
 * 16進数カラーをRGBA形式に変換
 * @param {string} hex - 16進数カラー（#RRGGBB または #RGB）
 * @param {number} alpha - 透明度（0-1）
 * @returns {string} rgba形式の色文字列
 */
export const hexToRgba = (hex, alpha = 1) => {
  if (!hex || hex === "transparent") {
    return `rgba(0, 0, 0, 0)`;
  }

  let r, g, b;

  if (hex.startsWith("rgb")) {
    const match = hex.match(/rgba?\((\d+),\s*(\d+),\s*(\d+)/);
    if (match) {
      r = parseInt(match[1], 10);
      g = parseInt(match[2], 10);
      b = parseInt(match[3], 10);
      return `rgba(${r}, ${g}, ${b}, ${alpha})`;
    }
    return hex;
  }

  hex = hex.replace("#", "");

  if (hex.length === 3) {
    hex = hex
      .split("")
      .map((c) => c + c)
      .join("");
  }

  r = parseInt(hex.slice(0, 2), 16);
  g = parseInt(hex.slice(2, 4), 16);
  b = parseInt(hex.slice(4, 6), 16);

  return `rgba(${r}, ${g}, ${b}, ${alpha})`;
};

/**
 * RGBA形式から色とalpha値を抽出
 * @param {string} rgba - rgba形式の色文字列
 * @returns {Object} { color: string, alpha: number }
 */
export const parseRgba = (rgba) => {
  if (!rgba) {
    return { color: "", alpha: 1 };
  }

  if (rgba === "transparent") {
    return { color: "transparent", alpha: 0 };
  }

  const match = rgba.match(/rgba?\((\d+),\s*(\d+),\s*(\d+)(?:,\s*([\d.]+))?\)/);
  if (match) {
    const r = parseInt(match[1], 10);
    const g = parseInt(match[2], 10);
    const b = parseInt(match[3], 10);
    const alpha = match[4] !== undefined ? parseFloat(match[4]) : 1;

    const hex = `#${r.toString(16).padStart(2, "0")}${g.toString(16).padStart(2, "0")}${b.toString(16).padStart(2, "0")}`;
    return { color: hex, alpha };
  }

  if (rgba.startsWith("#")) {
    return { color: rgba, alpha: 1 };
  }

  return { color: rgba, alpha: 1 };
};

/**
 * CustomColorPalette Component
 *
 * @param {Object} props
 * @param {string} props.color - 現在の色の値（hex形式）
 * @param {number} props.alpha - 透明度（0-1）
 * @param {string} props.gradient - グラデーション値
 * @param {boolean} props.enableGradient - グラデーション切り替えを有効にするか
 * @param {boolean} props.enableAlpha - alpha設定を有効にするか
 * @param {boolean} props.enableTransparent - 透明オプションを表示するか
 * @param {Function} props.onColorChange - 色変更時のコールバック関数
 * @param {Function} props.onAlphaChange - alpha変更時のコールバック関数
 * @param {Function} props.onGradientChange - グラデーション変更時のコールバック関数
 * @param {Function} props.onUseGradientChange - グラデーション使用切り替え時のコールバック関数
 * @param {boolean} props.useGradient - グラデーションを使用中かどうか
 * @param {string} props.label - ラベルテキスト（オプション）
 * @returns {JSX.Element}
 */
const ColorCircle = ({ color, name, isSelected, onClick, isTransparent }) => {
  const checkeredPattern = "url(\"data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='8' height='8'%3E%3Crect width='4' height='4' fill='%23ccc'/%3E%3Crect x='4' y='4' width='4' height='4' fill='%23ccc'/%3E%3C/svg%3E\")";
  
  return (
    <button
      type="button"
      onClick={onClick}
      title={name}
      style={{
        width: "28px",
        height: "28px",
        borderRadius: "50%",
        border: isSelected ? "2px solid #2669e6" : "1px solid rgba(0,0,0,0.1)",
        background: isTransparent ? checkeredPattern : color,
        cursor: "pointer",
        padding: 0,
        boxShadow: isSelected ? "0 0 0 2px #fff, 0 0 0 4px #2669e6" : "inset 0 0 0 1px rgba(0,0,0,0.1)",
        position: "relative",
        display: "flex",
        alignItems: "center",
        justifyContent: "center",
      }}
    >
      {isSelected && (
        <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke={isTransparent || color === "#FFFFFF" || color === "#ffffff" ? "#333" : "#fff"} strokeWidth="3" strokeLinecap="round" strokeLinejoin="round">
          <polyline points="20 6 9 17 4 12" />
        </svg>
      )}
    </button>
  );
};

const AddColorButton = () => {
  const handleClick = () => {
    const adminUrl = window.zenBlocks?.adminUrl || window.location.origin + "/wp-admin/";
    const isBlockTheme = window.zenBlocks?.isBlockTheme;
    if (isBlockTheme) {
      window.open(adminUrl + "site-editor.php?p=%2Fstyles&section=%2Fcolors%2Fpalette", "_blank");
    } else {
      window.open(adminUrl + "customize.php", "_blank");
    }
  };

  return (
    <button
      type="button"
      onClick={handleClick}
      style={{
        display: "flex",
        alignItems: "center",
        gap: "6px",
        padding: "6px 12px",
        border: "1px solid #ddd",
        borderRadius: "4px",
        background: "#f6f7f7",
        cursor: "pointer",
        fontSize: "12px",
        color: "#1e1e1e",
      }}
    >
      <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
        <path d="M11 4H4a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2v-7" />
        <path d="M18.5 2.5a2.121 2.121 0 0 1 3 3L12 15l-4 1 1-4 9.5-9.5z" />
      </svg>
      {__("Edit Palette", "zenblocks")}
    </button>
  );
};

const CustomColorPaletteGrid = ({ colors, selectedColor, onColorChange, enableAddButton }) => {
  return (
    <div style={{ display: "flex", flexWrap: "wrap", gap: "8px" }}>
      {colors.map((c, index) => (
        <ColorCircle
          key={index}
          color={c.color}
          name={c.name}
          isSelected={selectedColor === c.color}
          isTransparent={c.color === "transparent"}
          onClick={() => onColorChange(c.color)}
        />
      ))}
      {enableAddButton && <AddColorButton />}
    </div>
  );
};

const CustomColorPalette = ({
  color,
  alpha = 1,
  gradient,
  enableGradient = false,
  enableAlpha = true,
  enableAddButton = true,
  onColorChange,
  onAlphaChange,
  onGradientChange,
  onUseGradientChange,
  useGradient = false,
  label,
}) => {
  const [themeColors = [], customColors = [], themeGradients = [], customGradients = []] = useSettings(
    "color.palette.theme",
    "color.palette.custom",
    "color.gradients.theme",
    "color.gradients.custom"
  );

  const allColors = [
    ...themeColors.map((c) => ({
      name: c.name,
      color: c.color,
    })),
    ...customColors.map((c) => ({
      name: c.name,
      color: c.color,
    })),
  ];

  const allGradients = [
    ...themeGradients.map((g) => ({
      name: g.name,
      gradient: g.gradient,
    })),
    ...customGradients.map((g) => ({
      name: g.name,
      gradient: g.gradient,
    })),
  ];

  const handleColorChange = (value) => {
    if (value === undefined || value === null) {
      onColorChange && onColorChange("transparent");
      onAlphaChange && onAlphaChange(0);
    } else {
      onColorChange && onColorChange(value);
      if (value === "transparent") {
        onAlphaChange && onAlphaChange(0);
      }
    }
  };

  const handleAlphaChange = (value) => {
    onAlphaChange && onAlphaChange(value);
  };

  const handleGradientChange = (value) => {
    onGradientChange && onGradientChange(value);
  };

  const handleModeChange = (mode) => {
    onUseGradientChange && onUseGradientChange(mode === "gradient");
  };

  return (
    <div className="zenblocks-custom-color-palette">
      {label && <label style={{ display: "block", marginBottom: "8px", fontSize: "11px", fontWeight: "500", textTransform: "uppercase" }}>{label}</label>}

      {enableGradient && (
        <div className="zenblocks-custom-color-palette__tabs">
          <button
            type="button"
            className={`zenblocks-custom-color-palette__tab ${!useGradient ? "is-active" : ""}`}
            onClick={() => handleModeChange("color")}
          >
            {__("Color", "zenblocks")}
          </button>
          <button
            type="button"
            className={`zenblocks-custom-color-palette__tab ${useGradient ? "is-active" : ""}`}
            onClick={() => handleModeChange("gradient")}
          >
            {__("Gradient", "zenblocks")}
          </button>
        </div>
      )}

      {enableGradient && useGradient ? (
        <>
          <GradientPicker value={gradient || "linear-gradient(135deg, #007FD6 0%, #02439D 100%)"} onChange={handleGradientChange} gradients={allGradients.length > 0 ? allGradients : undefined} />
          {enableAddButton && (
            <div className="zenblocks-custom-color-palette__edit-button">
              <AddColorButton />
            </div>
          )}
        </>
      ) : (
        <>
          <ColorPalette value={color === "transparent" ? undefined : color} onChange={handleColorChange} disableCustomColors={false} clearable={true} colors={allColors} />
          {enableAddButton && (
            <div className="zenblocks-custom-color-palette__edit-button">
              <AddColorButton />
            </div>
          )}

          {enableAlpha && (
            <RangeControl
              label={__("Opacity", "zenblocks")}
              value={alpha}
              onChange={handleAlphaChange}
              min={0}
              max={1}
              step={0.01}
              style={{ marginTop: "12px" }}
            />
          )}
        </>
      )}
    </div>
  );
};

export default CustomColorPalette;
