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

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

  // Form state
  const [username, setUsername] = useState('')
  const [password, setPassword] = useState('')
  const [role, setRole] = useState('user')
  const [formLoading, setFormLoading] = useState(false)
  const [formError, setFormError] = 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 resetForm = () => {
    setUsername('')
    setPassword('')
    setRole('user')
    setFormError('')
    setShowAddUser(false)
    setEditingUser(null)
  }

  const handleAddUser = async (e) => {
    e.preventDefault()
    setFormError('')
    setFormLoading(true)

    try {
      await createUser(token, { username, password, role })
      await fetchUsers()
      resetForm()
    } catch (err) {
      setFormError(err.message || 'Failed to create user')
    } finally {
      setFormLoading(false)
    }
  }

  const handleUpdateUser = async (e) => {
    e.preventDefault()
    setFormError('')
    setFormLoading(true)

    try {
      // Update role if changed
      if (role !== editingUser.role) {
        await updateUserRole(token, editingUser.id, role)
      }
      // Update password if provided
      if (password) {
        await updateUserPassword(token, editingUser.id, password)
      }
      await fetchUsers()
      resetForm()
    } catch (err) {
      setFormError(err.message || 'Failed to update user')
    } finally {
      setFormLoading(false)
    }
  }

  const handleDeleteUser = async (userId) => {
    if (!confirm('Are you sure you want to delete this user?')) return

    try {
      await deleteUser(token, userId)
      await fetchUsers()
    } catch (err) {
      setError(err.message || 'Failed to delete user')
    }
  }

  const startEdit = (user) => {
    setEditingUser(user)
    setUsername(user.username)
    setRole(user.role)
    setPassword('')
    setShowAddUser(false)
  }

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

  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 mb-4">
              {users.map((user) => (
                <div key={user.id} className="card p-3 flex items-center justify-between">
                  <div>
                    <div className="text-white font-medium">{user.username}</div>
                    <div className="text-xs text-neutral-500">{roleLabels[user.role]}</div>
                  </div>
                  <div className="flex gap-2">
                    <button
                      onClick={() => startEdit(user)}
                      className="btn btn-ghost text-sm"
                    >
                      Edit
                    </button>
                    <button
                      onClick={() => handleDeleteUser(user.id)}
                      className="btn btn-ghost text-sm text-red-400"
                    >
                      Delete
                    </button>
                  </div>
                </div>
              ))}
            </div>
          )}

          {/* Add/Edit Form */}
          {(showAddUser || editingUser) ? (
            <form onSubmit={editingUser ? handleUpdateUser : handleAddUser} className="space-y-4">
              <div className="border-t border-neutral-800 pt-4">
                <h3 className="text-sm font-medium text-neutral-300 mb-3">
                  {editingUser ? 'Edit User' : 'Add New User'}
                </h3>

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

                {!editingUser && (
                  <div className="form-group">
                    <label className="form-label">Username</label>
                    <input
                      type="text"
                      value={username}
                      onChange={(e) => setUsername(e.target.value)}
                      className="input"
                      required
                    />
                  </div>
                )}

                <div className="form-group">
                  <label className="form-label">
                    {editingUser ? 'New Password (leave empty to keep current)' : 'Password'}
                  </label>
                  <input
                    type="password"
                    value={password}
                    onChange={(e) => setPassword(e.target.value)}
                    className="input"
                    required={!editingUser}
                  />
                </div>

                <div className="form-group">
                  <label className="form-label">Role</label>
                  <select
                    value={role}
                    onChange={(e) => setRole(e.target.value)}
                    className="select w-full"
                  >
                    <option value="user">Viewer</option>
                    <option value="moderator">Operator</option>
                    <option value="superadmin">Admin</option>
                  </select>
                </div>

                <div className="flex gap-2">
                  <button
                    type="submit"
                    disabled={formLoading}
                    className="btn btn-primary flex-1"
                  >
                    {formLoading ? 'Saving...' : (editingUser ? 'Update User' : 'Add User')}
                  </button>
                  <button
                    type="button"
                    onClick={resetForm}
                    className="btn btn-secondary"
                  >
                    Cancel
                  </button>
                </div>
              </div>
            </form>
          ) : (
            <button
              onClick={() => setShowAddUser(true)}
              className="btn btn-primary w-full"
            >
              Add User
            </button>
          )}
        </div>
      </div>
    </div>
  )
}
