import React, {useState} from 'react'
import router from 'next/router'
import Link from 'next/link'
import {DateTime} from 'luxon'
import {Icon} from '@rmwc/icon'
import axios from 'axios'
import useUser, {useSetUser} from '~/hooks/useUser'
import AdminToolbar from '~/components/admin/actionBar'
import Table from '~/components/table'
UsersTable.getInitialProps = async ({ctx: {axios}}) => {
const {data: users} = await axios.get(`/api/users`)
return {users}
}
export default function UsersTable({users: _users}) {
const currentUser = useUser()
const setCurrentUser = useSetUser()
const [users, setUsers] = useState(_users)
const promoteAdmin = uuid => async ev => {
if(ev) ev.preventDefault()
if(!window.confirm(`Are you sure you want to make this user an admin?`))
return
const {data: user} = await axios.put(`/api/users/${uuid}/admin`)
if(user.uuid === currentUser.uuid)
setCurrentUser(user)
setUsers(users.map(u => u.uuid === uuid ? user : u))
}
const demoteAdmin = uuid => async ev => {
if(ev) ev.preventDefault()
if(!window.confirm(`Are you sure you want to demote this user?`))
return
const {data: user} = await axios.delete(`/api/users/${uuid}/admin`)
if(user.uuid === currentUser.uuid){
setCurrentUser(user)
router.push('/')
}
setUsers(users.map(u => u.uuid === uuid ? user : u))
}
return (
<>