import React, { useState, useRef, useEffect } from 'react';
import { __ } from '@wordpress/i18n';

/**
 * InlineToolbarButton - インラインツールバー用のボタンコンポーネント
 * 
 * @param {Object} props
 * @param {string} props.icon - SVGアイコンのパス（d属性）またはカスタムSVG要素
 * @param {Function} props.onClick - クリックハンドラー
 * @param {boolean} props.isActive - アクティブ状態
 * @param {string} props.title - ツールチップタイトル
 * @param {boolean} props.disabled - 無効状態
 * @param {Object} props.customIcon - カスタムアイコン設定（viewBox、strokeWidth等）
 * @param {boolean} props.hasDropdown - ドロップダウンを持つかどうか
 * @param {React.Component} props.dropdownContent - ドロップダウンの内容
 */
export const InlineToolbarButton = ({
  icon,
  onClick,
  isActive = false,
  title,
  disabled = false,
  customIcon = {},
  hasDropdown = false,
  dropdownContent = null,
  showDropdown: externalShowDropdown,
  onDropdownToggle,
}) => {
  const [internalShowDropdown, setInternalShowDropdown] = useState(false);
  
  // 外部制御される場合は外部の状態を使用、そうでなければ内部状態を使用
  const showDropdown = externalShowDropdown !== undefined ? externalShowDropdown : internalShowDropdown;
  const setShowDropdown = onDropdownToggle || setInternalShowDropdown;
  const buttonRef = useRef(null);
  const dropdownRef = useRef(null);
  const buttonStyle = {
    background: isActive ? 'rgba(59, 130, 246, 0.5)' : 'transparent',
    border: 'none',
    borderRadius: '6px',
    color: disabled ? '#666' : '#ffffff',
    cursor: disabled ? 'not-allowed' : 'pointer',
    width: '32px',
    height: '32px',
    display: 'flex',
    alignItems: 'center',
    justifyContent: 'center',
    transition: 'all 0.2s cubic-bezier(0.175, 0.885, 0.32, 1.275)',
    padding: '0',
    fontSize: '0',
    outline: 'none',
    opacity: disabled ? 0.5 : 1,
  };

  const handleMouseEnter = (e) => {
    if (!disabled) {
      e.target.style.background = isActive ? 'rgba(59, 130, 246, 0.6)' : 'rgba(59, 130, 246, 0.3)';
      e.target.style.transform = 'scale(1.05)';
    }
  };

  const handleMouseLeave = (e) => {
    if (!disabled) {
      e.target.style.background = isActive ? 'rgba(59, 130, 246, 0.5)' : 'transparent';
      e.target.style.transform = 'scale(1)';
    }
  };

  // ドロップダウンの外側クリックで閉じる
  useEffect(() => {
    const handleClickOutside = (event) => {
      if (
        dropdownRef.current &&
        !dropdownRef.current.contains(event.target) &&
        buttonRef.current &&
        !buttonRef.current.contains(event.target)
      ) {
        setShowDropdown(false);
      }
    };

    if (showDropdown && hasDropdown) {
      document.addEventListener('click', handleClickOutside);
      return () => document.removeEventListener('click', handleClickOutside);
    }
  }, [showDropdown, hasDropdown]);

  const handleClick = (e) => {
    if (disabled) return;
    
    if (hasDropdown) {
      setShowDropdown(!showDropdown);
    } else if (onClick) {
      onClick(e);
    }
  };

  // カスタムSVG要素の場合はそのまま使用
  if (React.isValidElement(icon)) {
    return (
      <div style={{ position: 'relative' }}>
        <button
          ref={buttonRef}
          style={buttonStyle}
          onClick={handleClick}
          onMouseEnter={handleMouseEnter}
          onMouseLeave={handleMouseLeave}
          title={title}
          disabled={disabled}
          aria-label={title}
          aria-pressed={isActive}
        >
          {icon}
        </button>
        {hasDropdown && showDropdown && (
          <div ref={dropdownRef}>
            {dropdownContent}
          </div>
        )}
      </div>
    );
  }

  // パス文字列の場合はSVG要素を生成
  const {
    viewBox = '0 0 24 24',
    width = 18,
    height = 18,
    strokeWidth = 2,
    fill = 'none',
    strokeLinecap = 'round',
    strokeLinejoin = 'round'
  } = customIcon;

  return (
    <div style={{ position: 'relative' }}>
      <button
        ref={buttonRef}
        style={buttonStyle}
        onClick={handleClick}
        onMouseEnter={handleMouseEnter}
        onMouseLeave={handleMouseLeave}
        title={title}
        disabled={disabled}
        aria-label={title}
        aria-pressed={isActive}
      >
        <svg
          width={width}
          height={height}
          viewBox={viewBox}
          fill={fill}
          stroke="currentColor"
          strokeWidth={strokeWidth}
          strokeLinecap={strokeLinecap}
          strokeLinejoin={strokeLinejoin}
        >
          {typeof icon === 'string' && <path d={icon} />}
        </svg>
      </button>
      {hasDropdown && showDropdown && (
        <div ref={dropdownRef}>
          {dropdownContent}
        </div>
      )}
    </div>
  );
};

export default InlineToolbarButton;