<template>
  <div class="mt-5">
    <Modal v-if="actionModal.open" :title="actionModal.title" @click="actionModal.func">
      <Select v-model="actionModal.reason" :options="[{ name: 'Griefing', value: 'griefing' }]">Reason</Select>
    </Modal>
    <h1 class="text-2xl font-bold text-primary">
      Users
    </h1>
    <div class="mx-auto my-10 max-w-4xl">
      <h2 class="mb-2 text-xl font-bold text-primary">User Actions</h2>
      <div class="w-full rounded border-[1px] border-primary px-3 py-1 text-left">
        <table class="w-full table-auto divide-y divide-neutral-500 rounded">
          <tr class="border-b-2 border-primary text-gray-200">
            <th class="py-1">Username</th>
            <th class="py-1">Team</th>
            <th class="py-1">MC Linked</th>
            <th class="py-1">Actions</th>
          </tr>
          <tr v-for="user in users" :key="user._id" class="text-gray-200">
            <td class="py-1">{{ user.username }}</td>
            <td class="py-1">{{ user.team ? teams.filter(a => a._id === user.team.id)[0].name : '-' }}</td>
            <td class="py-1">{{ user.minecraft.uuid ? 'True ' : 'False' }}</td>
            <td class="space-x-2 py-1">
              <span v-if="currentUser.role.admin" class="rounded bg-red-700 px-2 text-red-300 hover:cursor-pointer hover:bg-red-800" @click="openModal(user, 'ban', ban(user))">Ban</span>
              <span class="rounded bg-orange-700 px-2 text-orange-300 hover:cursor-pointer hover:bg-orange-800">Suspend</span>
              <span class="rounded bg-yellow-700 px-2 text-yellow-300 hover:cursor-pointer hover:bg-yellow-800">Warn</span>
            </td>
          </tr>
        </table>
      </div>
    </div>
  </div>
</template>

<script setup>
definePageMeta({
  middleware: ["auth"],
  moderator: true
})

useHead({ title: 'Users | Polarcraft' })

const currentUser = useState('user')

const { data: users } = useFetch('/api/auth/getusers')
const { data: teams } = useFetch('/api/team/all')

const actionModal = ref({
  open: false,
  title: '',
  reason: '',
  userId: '',
  func: null,
})

const openModal = (user, type, func) => {
  if (type === 'ban') actionModal.value.title = 'Ban User'
  if (type === 'suspend') actionModal.value.title = 'Suspend User'
  if (type === 'warn') actionModal.value.title = 'Warn User'

  actionModal.value.func = func
  actionModal.value.userId = user._id; 
  actionModal.value.open = true
}

const ban = async (user) => {
  try {
    const response = await $fetch(`/api/auth/user/${user._id}/ban`, {
      reason: "reason"
    })

    user = response;
  } catch (e) {
    console.log(e);
    useToast().error('Error banning user')
  }
}
</script>
