<script setup lang="ts">
import { showAlert } from '@/alerts';
import { AnnouncementAPIClient } from '@/api/announcement';
import { AuthenticationAPIClient, type User, type UserUpdatePayload } from '@/api/auth';
import ConfirmDialog from '@/components/ConfirmDialog.vue';
import { useAuthStore } from '@/stores/auth';
import { onMounted, ref, useTemplateRef, watch, 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: '' })

interface CreateAnnouncementFormData {
  type: string
  message: string
}
const createAnnouncementFormData: Ref<CreateAnnouncementFormData> = ref({ type: 'INFO', message: '' })

const users: Ref<User[]> = ref([])
const usersPage: Ref<number> = ref(0)
const usersPageSize: Ref<number> = ref(50)

const deleteUserConfirmDialog = useTemplateRef('deleteUserConfirmDialog')

onMounted(() => {
  watch([usersPage, usersPageSize], fetchUsers)
  fetchUsers()
})

async function fetchUsers() {
  const result = await apiClient.getUsers(usersPage.value, usersPageSize.value).handleErrorsWithAlert()
  if (result !== null) {
    users.value = result
  }
}

async function deleteUser(user: User) {
  const confirm = await deleteUserConfirmDialog.value?.show()
  if (!confirm) return
  await apiClient.deleteUser(user.id).handleErrorsWithAlert()
  fetchUsers() // Refresh the list of users.
}

async function toggleLocked(user: User) {
  const payload: UserUpdatePayload = {
    isLocked: !user.isLocked
  }
  await apiClient.updateUser(user.id, payload).handleErrorsWithAlert()
  fetchUsers()
}

async function doCreateUser() {
  const user = await apiClient.createUser(createUserFormData.value.username, createUserFormData.value.password)
    .handleErrorsWithAlert()
  if (user !== null) {
    createUserFormData.value = {
      username: '',
      password: ''
    }
    fetchUsers();
  }
}

async function doCreateAnnouncement() {
  const client = new AnnouncementAPIClient(authStore)
  const a = await client.createAnnouncement(
    createAnnouncementFormData.value.type, createAnnouncementFormData.value.message
  ).handleErrorsWithAlert()
  if (a !== null) {
    await showAlert('Created announcement. It will appear shortly.')
    createAnnouncementFormData.value = { type: 'INFO', message: '' }
  }
}
</script>
<template>
  <main>
    <h1>Administrator Dashboard</h1>
    <p>
      On this page, you'll find tools for managing users and checking audit information.
    </p>

    <h3>Users</h3>
    <div class="button-bar">
      <button type="button" :disabled="usersPage < 1" @click="usersPage -= 1">Previous Page</button>
      <span>Page: {{ usersPage }}</span>
      <button type="button" @click="usersPage += 1">Next Page</button>
      <select v-model="usersPageSize">
        <option value="5">5</option>
        <option value="10">10</option>
        <option value="50" selected>50</option>
        <option value="100">100</option>
      </select>
    </div>
    <table>
      <thead>
        <tr>
          <th>ID</th>
          <th>Username</th>
          <th>Created At</th>
          <th>Admin</th>
          <th>Locked</th>
          <th>Actions</th>
        </tr>
      </thead>
      <tbody>
        <tr v-for="user in users" :key="user.id">
          <td>{{ user.id }}</td>
          <td>{{ user.username }}</td>
          <td>{{ new Date(user.createdAt).toLocaleString() }}</td>
          <td>{{ user.isAdmin }}</td>
          <td>{{ user.isLocked }}</td>
          <td>
            <div>
              <button type="button" @click="deleteUser(user)">Delete</button>

              <button type="button" @click="toggleLocked(user)" v-text="user.isLocked ? 'Unlock' : 'Lock'"></button>

            </div>
          </td>
        </tr>
      </tbody>
    </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>

    <form @submit.prevent="doCreateAnnouncement">
      <h3>Create Announcement</h3>
      <div>
        <label for="create-announcement-type">Type</label>
        <select id="create-announcement-type" v-model="createAnnouncementFormData.type">
          <option value="INFO" selected>INFO</option>
          <option value="ERROR">ERROR</option>
        </select>
      </div>
      <div>
        <label for="create-announcement-message">Message</label>
        <textarea id="create-announcement-message" v-model="createAnnouncementFormData.message" maxlength="2000"
          minlength="1" required style="min-width: 300px; min-height: 100px;"></textarea>
      </div>
      <div>
        <button type="submit">Create</button>
      </div>
    </form>

    <ConfirmDialog ref="deleteUserConfirmDialog">
      <p>
        Are you sure you want to delete this user?
      </p>
    </ConfirmDialog>
  </main>
</template>
