/**
 * SVG Icon Selector Component
 *
 * A reusable component for selecting SVG icons in block settings.
 *
 * 新しいインターフェース（推奨）:
 * iconSizes: { pc: 24, mobile: 18 }
 * onIconSizesChange: (newSizes) => {}
 * inheritSizes: { pc: false, mobile: false }
 * onInheritSizesChange: (newInheritSizes) => {}
 *
 * 古いインターフェース（後方互換性のため保持）:
 * iconSize: 24
 * onIconSizeChange: (newSize) => {}
 * inheritSize: false
 * onInheritSizeChange: (newInherit) => {}
 */

import { useState, useEffect, useRef } from "@wordpress/element";
import { BaseControl, Button } from "@wordpress/components";
import { __ } from "@wordpress/i18n";
import { ResponsiveTabProvider } from "../../ResponsiveTabContext";
import ResponsiveControl from "../../ResponsiveControl";

// 分割されたモジュールをインポート
import { renderSVGIcon, renderIconForSelector } from "./SVGIconSetting/IconRenderer";
import { IconSizeControl } from "./SVGIconSetting/SizeControls";
import { IconModal } from "./SVGIconSetting/IconModal";
import { getIconCategory } from "./SVGIconSetting/utils";

// インライン表示用のスタイルをインポート
import "./SVGIconSetting/inline-selector.css";

// renderSVGIcon関数をエクスポート（後方互換性のため）
export { renderSVGIcon };

/**
 * アイコン選択コンポーネント
 * @param {Object} props - コンポーネントのプロパティ
 */
export default function SVGIconSetting({
  label,
  value,
  onChange,
  help,
  color = "#FFFFFF",
  onColorChange,
  strokeWidth = 1.75,
  onStrokeWidthChange,
  iconSizePC = 24,
  iconSizeSP = 18,
  onIconSizePCChange,
  onIconSizeSPChange,
  inheritSizePC = false,
  inheritSizeSP = false,
  onInheritSizePCChange,
  onInheritSizeSPChange,
  activeTab = "pc",
  // 以下は後方互換性のため（非推奨）
  iconSize,
  onIconSizeChange,
  inheritSize,
  onInheritSizeChange,
  // 新しいインターフェース（使用されている場合）
  inheritSizes,
  onInheritSizesChange,
}) {
  const [isPopoverVisible, setIsPopoverVisible] = useState(false);
  const [lucideStrokeWidth, setLucideStrokeWidth] = useState(strokeWidth);
  const buttonRef = useRef(null);

  // 外部からのstrokeWidth変更を常に反映
  useEffect(() => {
    setLucideStrokeWidth(strokeWidth);
  }, [strokeWidth]);

  // コンソールログでデバッグ情報を出力
  // console.log("SVGIconSetting stroke-width debug:", {
  //   externalStrokeWidth: strokeWidth,
  //   internalStrokeWidth: lucideStrokeWidth,
  //   value: value
  // });

  // inheritSizes 新しいインターフェースを使用するかどうかを判定
  const useInheritSizes = inheritSizes && onInheritSizesChange;

  /**
   * アイコンを選択
   * @param {string} iconKey - アイコン識別子
   */
  const selectIcon = (iconKey) => {
    onChange(iconKey);

    // アイコンを初めて設定する場合の初期値設定
    if (iconKey && iconKey !== "" && (!value || value === "")) {
      // アイコン色が未設定の場合、現在の色を初期値として設定
      if (onColorChange && (!color || color === "")) {
        // 既存の色が設定されていればそれを保持、未設定の場合は何もしない
      }
      // Feather、LucideアイコンまたはHeroiconsアウトライン、Tablerアウトライン、カスタムSVGの場合はデフォルトのstroke widthを設定
      // RemixIconはfill属性を使用するため、stroke-widthは適用されない
      if (
        (iconKey.startsWith("feather-") || iconKey.startsWith("lucide-") || iconKey.startsWith("heroicons-outline-") || iconKey.startsWith("tabler-outline-") || iconKey.startsWith("custom-svg-")) &&
        onStrokeWidthChange &&
        !strokeWidth
      ) {
        onStrokeWidthChange(1.75);
      }
    }
  };

  return (
    <BaseControl label={label} help={help}>
      <div className="svg-icon-setting" style={{ display: "flex", flexDirection: "column", position: "relative" }}>
        <div className="svg-icon-setting__controls" style={{ display: "flex", alignItems: "center", marginBottom: "10px", flexWrap: "wrap" }}>
          <div style={{ display: "flex", alignItems: "center", width: "100%" }}>
            <Button
              ref={buttonRef}
              variant={value ? "secondary" : "primary"}
              className={`icon-selection-button${value ? " has-icon" : ""}`}
              onClick={() => setIsPopoverVisible(!isPopoverVisible)}
              style={{
                display: "flex",
                alignItems: "center",
                flex: "1",
                height: "36px",
                marginBottom: "0",
              }}
            >
              {value && (
                <span
                  className="icon-preview-button"
                  style={{
                    display: "inline-flex",
                    width: "22px",
                    height: "22px",
                    marginRight: "8px",
                    alignItems: "center",
                    justifyContent: "center",
                    color: "transparent",
                    overflow: "hidden",
                    flexShrink: 0,
                    position: "relative",
                  }}
                >
                  <span
                    style={{
                      display: "inline-block",
                      width: "100%",
                      height: "100%",
                      maxWidth: "22px",
                      maxHeight: "22px",
                      overflow: "hidden",
                      position: "relative",
                    }}
                    dangerouslySetInnerHTML={{
                      __html: renderIconForSelector(value, "#333"),
                    }}
                  />
                </span>
              )}
              {value ? __("Change Icon", "zenblocks") : __("Select Icon", "zenblocks")}
            </Button>
          </div>
        </div>

        {/* アイコン選択画面をボタンのすぐ下にインライン表示 */}
        <IconModal
          isVisible={isPopoverVisible}
          onClose={() => setIsPopoverVisible(false)}
          onSelectIcon={selectIcon}
          onDeleteIcon={() => onChange("")}
          selectedIcon={value}
          lucideStrokeWidth={lucideStrokeWidth}
          anchorRef={buttonRef}
          color={color}
        />

        {value &&
          (() => {
            const supportsStrokeWidth =
              value.startsWith("feather-") ||
              value.startsWith("lucide-") ||
              value.startsWith("heroicons-outline-") ||
              value.startsWith("tabler-outline-") ||
              (value.startsWith("heroicons-") && !value.startsWith("heroicons-solid-")) ||
              (value.startsWith("tabler-") && !value.startsWith("tabler-solid-")) ||
              value.startsWith("custom-svg-");

            const isStrokelessIcon = value.startsWith("fa-") || value.startsWith("remixicon-") || value.startsWith("heroicons-solid-") || value.startsWith("tabler-solid-");

            if (supportsStrokeWidth) {
              return (
                <div style={{ marginTop: "10px", marginBottom: "10px" }}>
                  <div style={{ fontSize: "13px", color: "#333", marginBottom: "8px", fontWeight: "500" }}>
                    {__("Stroke width", "zenblocks")}
                    <span style={{ fontSize: "12px", fontWeight: "normal", color: "#666", marginLeft: "8px" }}>{lucideStrokeWidth}px</span>
                  </div>
                  <div style={{ display: "flex", alignItems: "center", gap: "12px" }}>
                    <span style={{ fontSize: "11px", color: "#666", minWidth: "20px", textAlign: "center" }}>0.5</span>
                    <input
                      type="range"
                      min="0.5"
                      max="3"
                      step="0.25"
                      value={lucideStrokeWidth}
                      onChange={(e) => {
                        const newValue = parseFloat(e.target.value);
                        setLucideStrokeWidth(newValue);
                        if (onStrokeWidthChange) {
                          onStrokeWidthChange(newValue);
                        }
                      }}
                      style={{
                        flex: 1,
                        height: "6px",
                        background: "#e0e0e0",
                        outline: "none",
                        borderRadius: "3px",
                        cursor: "pointer",
                        appearance: "none",
                        WebkitAppearance: "none",
                        border: "none",
                      }}
                    />
                    <span style={{ fontSize: "11px", color: "#666", minWidth: "20px", textAlign: "center" }}>3.0</span>
                  </div>
                </div>
              );
            } else if (isStrokelessIcon) {
              return (
                <div style={{ marginTop: "10px", marginBottom: "10px", padding: "8px 12px", backgroundColor: "#f0f0f0", borderRadius: "4px" }}>
                  <span style={{ fontSize: "12px", color: "#666" }}>{__("This icon does not support Stroke width changes", "zenblocks")}</span>
                </div>
              );
            }
            return null;
          })()}
      </div>
    </BaseControl>
  );
}
