import { useState, useEffect } from 'react'
import { useUser } from '../context/UserContext'
import { getUsers } from '../api'

function getDiscordProfileUrl(discordId) {
  return `https://discord.com/users/${discordId}`
}

export default function UserManagement({ onClose }) {
  const { token } = useUser()
  const [users, setUsers] = useState([])
  const [loading, setLoading] = useState(true)
  const [error, setError] = useState('')

  const fetchUsers = async () => {
    try {
      const data = await getUsers(token)
      setUsers(data)
      setError('')
    } catch (err) {
      setError('Failed to load users')
    } finally {
      setLoading(false)
    }
  }

  useEffect(() => {
    fetchUsers()
  }, [token])

  const getAvatarUrl = (user) => {
    const discordId = user.discord_id || user.discordId
    if (user.avatar && discordId) {
      return `https://cdn.discordapp.com/avatars/${discordId}/${user.avatar}.png?size=64`
    }
    // Default Discord avatar
    const defaultIndex = discordId ? parseInt(discordId) % 5 : 0
    return `https://cdn.discordapp.com/embed/avatars/${defaultIndex}.png`
  }

  const roleLabels = {
    user: 'Viewer',
    moderator: 'Operator',
    superadmin: 'Admin'
  }

  const roleColors = {
    user: 'text-gray-400',
    moderator: 'text-blue-400',
    superadmin: 'text-amber-400'
  }

  return (
    <div className="modal-backdrop fade-in" onClick={onClose}>
      <div className="modal fade-in-scale" style={{ maxWidth: '32rem' }} onClick={(e) => e.stopPropagation()}>
        <div className="modal-header">
          <h2 className="modal-title">User Management</h2>
          <button onClick={onClose} className="btn btn-ghost">
            Close
          </button>
        </div>

        <div className="modal-body">
          {error && (
            <div className="alert alert-error mb-4">{error}</div>
          )}

          {/* User List */}
          {loading ? (
            <div className="text-center py-4 text-neutral-400">Loading users...</div>
          ) : (
            <div className="space-y-2">
              {users.map((user) => {
                const discordId = user.discord_id || user.discordId
                const profileUrl = discordId ? getDiscordProfileUrl(discordId) : null

                return (
                  <div key={user.id} className="card p-3 flex items-center gap-3">
                    {profileUrl ? (
                      <a
                        href={profileUrl}
                        target="_blank"
                        rel="noopener noreferrer"
                        className="flex-shrink-0"
                      >
                        <img
                          src={getAvatarUrl(user)}
                          alt={user.username}
                          className="w-10 h-10 rounded-full hover:ring-2 hover:ring-blue-500 transition-all"
                        />
                      </a>
                    ) : (
                      <img
                        src={getAvatarUrl(user)}
                        alt={user.username}
                        className="w-10 h-10 rounded-full"
                      />
                    )}
                    <div className="flex-1 min-w-0">
                      {profileUrl ? (
                        <a
                          href={profileUrl}
                          target="_blank"
                          rel="noopener noreferrer"
                          className="text-white font-medium truncate block hover:text-blue-400 transition-colors"
                        >
                          {user.username}
                        </a>
                      ) : (
                        <div className="text-white font-medium truncate">{user.username}</div>
                      )}
                      <div className="flex items-center gap-2 text-xs">
                        <span className={roleColors[user.role] || 'text-neutral-500'}>
                          {roleLabels[user.role]}
                        </span>
                      </div>
                    </div>
                  </div>
                )
              })}
            </div>
          )}

          {/* Info about Discord management */}
          <div className="mt-4 p-3 bg-neutral-800/50 rounded-lg border border-neutral-700">
            <p className="text-xs text-neutral-400">
              Benutzer und Rollen werden über Discord verwaltet.
            </p>
          </div>
        </div>
      </div>
    </div>
  )
}
