<script setup lang="ts">
import { AuthenticationAPIClient } from '@/api/auth';
import AdminAnnouncementCreator from '@/components/AdminAnnouncementCreator.vue';
import AdminUsersTable from '@/components/AdminUsersTable.vue';
import { useAuthStore } from '@/stores/auth';
import { ref, useTemplateRef, type Ref } from 'vue';

const authStore = useAuthStore()
const apiClient = new AuthenticationAPIClient(authStore)

interface CreateUserData {
  username: string
  password: string
}
const createUserFormData: Ref<CreateUserData> = ref({ username: '', password: '' })


const usersTable = useTemplateRef('admin-users-table')

async function doCreateUser() {
  const user = await apiClient.createUser(createUserFormData.value.username, createUserFormData.value.password)
    .handleErrorsWithAlert()
  if (user !== null) {
    createUserFormData.value = {
      username: '',
      password: ''
    }
    usersTable.value?.fetchUsers()
  }
}
</script>
<template>
  <main>
    <h1>Administrator Dashboard</h1>
    <p>
      On this page, you'll find tools for managing users and checking audit information.
    </p>

    <AdminUsersTable ref="admin-users-table" />

    <form @submit.prevent="doCreateUser">
      <h3>Create User</h3>
      <div>
        <label for="create-user-username">Username</label>
        <input id="create-user-username" v-model="createUserFormData.username" type="text" />
      </div>
      <div>
        <label for="create-user-password">Password</label>
        <input id="create-user-password" v-model="createUserFormData.password" type="password" />
      </div>
      <div>
        <button type="submit">Create</button>
      </div>
    </form>

    <AdminAnnouncementCreator />
  </main>
</template>
