import { useState, useEffect } from 'react'
import { getEventMembers, inviteEventMember, removeMember, updateMemberRole } from '../api/api'
import './EventMembers.css'

const he = {
  manageMembers: 'ניהול חברים',
  close: 'סגור',
  loading: '...טוען',
  failedLoadMembers: 'נכשל בטעינת חברים',
  members: 'חברים',
  email: 'אימייל',
  role: 'תפקיד',
  actions: 'פעולות',
  remove: 'הסר',
  inviteEmail: 'הזמן אימייל',
  inviteRole: 'תפקיד',
  invite: 'הזמן',
  emailRequired: 'אנא הזן כתובת אימייל',
  failedInvite: 'נכשל בהזמנה',
  failedRemove: 'נכשל בהסרת חבר'
}

function EventMembers({ eventId, onClose }) {
  const [members, setMembers] = useState([])
  const [loading, setLoading] = useState(true)
  const [error, setError] = useState('')
  const [inviteEmail, setInviteEmail] = useState('')
  const [inviteRole, setInviteRole] = useState('editor')
  const [inviting, setInviting] = useState(false)

  useEffect(() => {
    loadMembers()
  }, [eventId])

  const loadMembers = async () => {
    try {
      setLoading(true)
      const data = await getEventMembers(eventId)
      setMembers(data)
      setError('')
    } catch (err) {
      setError(he.failedLoadMembers)
      console.error(err)
    } finally {
      setLoading(false)
    }
  }

  const handleInvite = async (e) => {
    e.preventDefault()
    
    if (!inviteEmail.trim()) {
      setError(he.emailRequired)
      return
    }

    setInviting(true)
    setError('')

    try {
      await inviteEventMember(eventId, {
        user_email: inviteEmail,
        role: inviteRole
      })
      setInviteEmail('')
      await loadMembers()
    } catch (err) {
      setError(err.response?.data?.detail || he.failedInvite)
    } finally {
      setInviting(false)
    }
  }

  const handleRemove = async (userId) => {
    if (!window.confirm('הסר חבר זה מהאירוע?')) {
      return
    }

    try {
      await removeMember(eventId, userId)
      await loadMembers()
    } catch (err) {
      setError(he.failedRemove)
      console.error(err)
    }
  }

  const handleRoleChange = async (userId, newRole) => {
    try {
      await updateMemberRole(eventId, userId, newRole)
      await loadMembers()
    } catch (err) {
      setError('Failed to update role')
      console.error(err)
    }
  }

  return (
    <div className="members-modal-overlay" onClick={onClose}>
      <div className="members-modal" onClick={(e) => e.stopPropagation()}>
        <div className="members-modal-header">
          <h2>{he.manageMembers}</h2>
          <button onClick={onClose} className="btn-close">✕</button>
        </div>

        <div className="members-content">
          {error && <div className="error-message">{error}</div>}

          <div className="invite-section">
            <h3>{he.inviteEmail}</h3>
            <form onSubmit={handleInvite}>
              <div className="invite-form">
                <input
                  type="email"
                  value={inviteEmail}
                  onChange={(e) => setInviteEmail(e.target.value)}
                  placeholder="הזן כתובת אימייל"
                  disabled={inviting}
                />
                <select 
                  value={inviteRole} 
                  onChange={(e) => setInviteRole(e.target.value)}
                  disabled={inviting}
                >
                  <option value="admin">ניהול</option>
                  <option value="editor">עריכה</option>
                  <option value="viewer">צפייה</option>
                </select>
                <button 
                  type="submit" 
                  disabled={inviting}
                  className="btn-invite"
                >
                  {inviting ? 'מזמין...' : he.invite}
                </button>
              </div>
            </form>
          </div>

          {loading ? (
            <div className="loading">{he.loading}</div>
          ) : members.length === 0 ? (
            <div className="no-members">אין חברים עדיין</div>
          ) : (
            <div className="members-list">
              <h3>{he.members} ({members.length})</h3>
              {members.map(member => (
                <div key={member.id} className="member-item">
                  <div className="member-info">
                    <div className="member-email">{member.user?.email || 'Unknown'}</div>
                    {member.display_name && (
                      <div className="member-name">{member.display_name}</div>
                    )}
                  </div>
                  <div className="member-actions">
                    <select
                      value={member.role}
                      onChange={(e) => handleRoleChange(member.user_id, e.target.value)}
                      className="role-select"
                    >
                      <option value="admin">ניהול</option>
                      <option value="editor">עריכה</option>
                      <option value="viewer">צפייה</option>
                    </select>
                    <button
                      onClick={() => handleRemove(member.user_id)}
                      className="btn-remove"
                      title="Remove member"
                    >
                      ✕
                    </button>
                  </div>
                </div>
              ))}
            </div>
          )}
        </div>
      </div>
    </div>
  )
}

export default EventMembers
