<script setup lang="ts">
import { NButton, NFlex, NSpace, NTag, useMessage } from 'naive-ui'
import { ref } from 'vue'

import { getAuthClient } from '@/api/auth_client'
import type { User } from '@/api/generated/crabs/evening_detective_server'
import HeaderMenu from '@/components/HeaderMenu.vue'

const client = getAuthClient()
const message = useMessage()

const users = ref<User[]>([])

async function getUsers() {
  const res = await client.GetUsers({})
  if (res.error != '') {
    message.error(res.error!)
    return
  }
  users.value = res.users!
}
getUsers()

async function addRole(userId: number, role: string) {
  const res = await client.AddUserRole({ id: userId, role: role })
  if (res.error != '') {
    message.error(res.error!)
    return
  }
  await getUsers()
}

async function deleteRole(userId: number, role: string) {
  const res = await client.DeleteUserRole({ id: userId, role: role })
  if (res.error != '') {
    message.error(res.error!)
    return
  }
  await getUsers()
}
</script>

<template>
  <div class="center-block-custom">
    <div class="width700">
      <div v-for="user in users" v-bind:key="user.id" class="user-block">
        <div class="user-field">
          Позывной: {{ user.username }}
        </div>
        <div class="user-field">
          Почта: {{ user.email }}
        </div>
        <div class="user-field">
          <n-space>
            Роли: <n-tag :bordered="false" v-for="role in user.roles" v-bind:key="role">
              {{ role }}
            </n-tag>
          </n-space>
        </div>
        <n-flex justify="end" class="roles-buttons-block">

          <n-button @click="addRole(user.id!, 'author')" v-if="!user.roles?.includes('author')">Сделать
            автором</n-button>
          <n-button @click="deleteRole(user.id!, 'author')" v-else>Забрать роль автора</n-button>

          <n-button @click="addRole(user.id!, 'organizer')" v-if="!user.roles?.includes('organizer')">Сделать
            организатором</n-button>
          <n-button @click="deleteRole(user.id!, 'organizer')" v-else>Забрать роль организатора</n-button>

        </n-flex>
      </div>
    </div>
  </div>

  <HeaderMenu active="users" />
</template>

<style scoped>
.user-block {
  border: 1px solid #444;
  border-radius: 10px;
  margin: 0 0 20px;
  padding: 20px;
}

.user-field {
  margin: 10px;
}

.roles-buttons-block {
  margin-top: 20px;
}
</style>
