import React, { useState, useEffect, useRef } from 'react'
import './BoardSelector.css'

function BoardSelector({
  boards,
  selectedBoardId,
  onBoardChange,
  onBoardEdit,
  onAddBoard,
  loading,
  showBoardAction = true
}) {
  const [isOpen, setIsOpen] = useState(false)
  const dropdownRef = useRef(null)

  const selectedBoard = boards.find(b => b.id === selectedBoardId)

  // Закрытие при клике снаружи
  useEffect(() => {
    const handleClickOutside = (e) => {
      if (dropdownRef.current && !dropdownRef.current.contains(e.target)) {
        setIsOpen(false)
      }
    }
    document.addEventListener('mousedown', handleClickOutside)
    return () => document.removeEventListener('mousedown', handleClickOutside)
  }, [])

  const handleSelectBoard = (board) => {
    onBoardChange(board.id)
    setIsOpen(false)
  }

  const handleBoardAction = (e) => {
    e.stopPropagation()
    setIsOpen(false)
    onBoardEdit()
  }

  return (
    <div className="board-selector" ref={dropdownRef}>
      <div className="board-header">
        <button
          className={`board-pill ${isOpen ? 'open' : ''}`}
          onClick={() => setIsOpen(!isOpen)}
          disabled={loading}
        >
          <span className="board-label">
            {loading ? 'Загрузка...' : (selectedBoard?.name || 'Выберите доску')}
          </span>
          {selectedBoard && (
            <span
              className="pill-action-btn"
              role="button"
              tabIndex={0}
              title={selectedBoard.is_owner ? 'Настройки доски' : 'Покинуть доску'}
              onClick={handleBoardAction}
              onKeyDown={(e) => e.key === 'Enter' && handleBoardAction(e)}
            >
              {selectedBoard.is_owner ? (
                <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
                  <circle cx="12" cy="12" r="1.5"></circle>
                  <circle cx="19" cy="12" r="1.5"></circle>
                  <circle cx="5" cy="12" r="1.5"></circle>
                </svg>
              ) : (
                <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
                  <path d="M9 21H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h4"></path>
                  <polyline points="16 17 21 12 16 7"></polyline>
                  <line x1="21" y1="12" x2="9" y2="12"></line>
                </svg>
              )}
            </span>
          )}
        </button>
      </div>

      <div className={`board-dropdown ${isOpen ? 'visible' : ''}`}>
        <div className="dropdown-content">
          {boards.length === 0 ? (
            <div className="dropdown-empty">
              Нет досок
            </div>
          ) : (
            <div className="dropdown-list">
              {boards.map(board => (
                <button
                  key={board.id}
                  className={`dropdown-item ${board.id === selectedBoardId ? 'selected' : ''}`}
                  onClick={() => handleSelectBoard(board)}
                >
                  <span className="item-name">{board.name}</span>
                  <div className="item-meta">
                    <span className={`item-members ${board.is_owner ? 'filled' : 'outline'}`}>{board.member_count + 1}</span>
                  </div>
                </button>
              ))}
            </div>
          )}

          <button className="dropdown-item add-board" onClick={onAddBoard}>
            <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
              <circle cx="12" cy="12" r="10"></circle>
              <line x1="12" y1="8" x2="12" y2="16"></line>
              <line x1="8" y1="12" x2="16" y2="12"></line>
            </svg>
            <span>Создать доску</span>
          </button>

          {selectedBoard && showBoardAction && (
            <button
              className="dropdown-item board-action-item"
              onClick={(e) => { setIsOpen(false); onBoardEdit() }}
            >
              {selectedBoard.is_owner ? (
                <>
                  <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
                    <circle cx="12" cy="12" r="3"></circle>
                    <path d="M19.4 15a1.65 1.65 0 0 0 .33 1.82l.06.06a2 2 0 0 1-2.83 2.83l-.06-.06a1.65 1.65 0 0 0-1.82-.33 1.65 1.65 0 0 0-1 1.51V21a2 2 0 0 1-4 0v-.09A1.65 1.65 0 0 0 9 19.4a1.65 1.65 0 0 0-1.82.33l-.06.06a2 2 0 0 1-2.83-2.83l.06-.06A1.65 1.65 0 0 0 4.68 15a1.65 1.65 0 0 0-1.51-1H3a2 2 0 0 1 0-4h.09A1.65 1.65 0 0 0 4.6 9a1.65 1.65 0 0 0-.33-1.82l-.06-.06a2 2 0 0 1 2.83-2.83l.06.06A1.65 1.65 0 0 0 9 4.68a1.65 1.65 0 0 0 1-1.51V3a2 2 0 0 1 4 0v.09a1.65 1.65 0 0 0 1 1.51 1.65 1.65 0 0 0 1.82-.33l.06-.06a2 2 0 0 1 2.83 2.83l-.06.06A1.65 1.65 0 0 0 19.4 9a1.65 1.65 0 0 0 1.51 1H21a2 2 0 0 1 0 4h-.09a1.65 1.65 0 0 0-1.51 1z"></path>
                  </svg>
                  <span>Настройки доски</span>
                </>
              ) : (
                <>
                  <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
                    <path d="M9 21H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h4"></path>
                    <polyline points="16 17 21 12 16 7"></polyline>
                    <line x1="21" y1="12" x2="9" y2="12"></line>
                  </svg>
                  <span>Покинуть доску</span>
                </>
              )}
            </button>
          )}
        </div>
      </div>
    </div>
  )
}

export default BoardSelector
