import React, { useState, useEffect } from 'react'
import { useAuth } from './auth/AuthContext'
import './BoardMembers.css'

function BoardMembers({ boardId, onMemberRemoved }) {
  const { authFetch } = useAuth()
  const [members, setMembers] = useState([])
  const [loading, setLoading] = useState(true)
  const [removingId, setRemovingId] = useState(null)
  
  useEffect(() => {
    if (boardId) {
      fetchMembers()
    }
  }, [boardId])
  
  const fetchMembers = async () => {
    try {
      const res = await authFetch(`/api/wishlist/boards/${boardId}/members`)
      if (res.ok) {
        const data = await res.json()
        setMembers(data || [])
      }
    } catch (err) {
      console.error('Error fetching members:', err)
    } finally {
      setLoading(false)
    }
  }
  
  const handleRemoveMember = async (userId) => {
    if (!window.confirm('Удалить участника из доски?')) return
    
    setRemovingId(userId)
    try {
      const res = await authFetch(`/api/wishlist/boards/${boardId}/members/${userId}`, {
        method: 'DELETE'
      })
      if (res.ok) {
        setMembers(members.filter(m => m.user_id !== userId))
        onMemberRemoved?.()
      }
    } catch (err) {
      console.error('Error removing member:', err)
    } finally {
      setRemovingId(null)
    }
  }
  
  const formatDate = (dateStr) => {
    const date = new Date(dateStr)
    return date.toLocaleDateString('ru-RU', {
      day: 'numeric',
      month: 'short',
      year: 'numeric'
    })
  }
  
  if (loading) {
    return (
      <div className="board-members-section">
        <h3>Участники</h3>
        <div className="members-loading">Загрузка...</div>
      </div>
    )
  }
  
  return (
    <div className="board-members-section">
      <h3>Участники ({members.length})</h3>
      
      {members.length === 0 ? (
        <div className="no-members">
          <p>Пока никто не присоединился к доске</p>
          <p className="hint">Поделитесь ссылкой, чтобы пригласить участников</p>
        </div>
      ) : (
        <div className="members-list">
          {members.map(member => (
            <div key={member.id} className="member-item">
              <div className="member-avatar">
                {(member.name || member.email).charAt(0).toUpperCase()}
              </div>
              <div className="member-info">
                <div className="member-name">
                  {member.name || member.email}
                </div>
                <div className="member-date">
                  Присоединился {formatDate(member.joined_at)}
                </div>
              </div>
              <button
                className="remove-member-btn"
                onClick={() => handleRemoveMember(member.user_id)}
                disabled={removingId === member.user_id}
                title="Удалить участника"
              >
                {removingId === member.user_id ? (
                  <span className="spinner-small"></span>
                ) : (
                  '✕'
                )}
              </button>
            </div>
          ))}
        </div>
      )}
    </div>
  )
}

export default BoardMembers

