<template>
   <n-message-provider>
        <FlashMessages 
            :messages="props.flashMessages"
        />
   </n-message-provider>
   <div class="flex flex-row-reverse mb-2">
      <n-button
         class="items-end"
         secondary
         type="primary"
         :renderIcon="() => { return renderIcon(Plus) }"
         :onClick="() => { router.get('/users/create') }"
      >
      Neuer Benutzer</n-button>
   </div>
   <n-data-table 
      :columns="columns"
      :data="users"
      row-class-name="group"
   />
</template>

<script setup>

import { h } from 'vue'
import BELayout from '@/layouts/BELayout.vue'
import FlashMessages from '@/components/FlashMessages.vue'
import { NIcon, NButton } from 'naive-ui'
import { router } from '@inertiajs/vue3'

import {
   AdminPanelSettingsFilled as Admin,
   EditRound as Edit,
   DeleteRound as Delete,
   PlusRound as Plus,
} from '@vicons/material'

defineOptions({ layout: BELayout })

const props = defineProps(['users', 'flashMessages'])

const columns = [
   {
      title: "Admin",
      key: "is_admin",
      align: "center",
      render (row) {
         if(row.is_admin) {
            return renderIcon(Admin, "align-middle")
         }
      }
   },
   {
      title: "Benutzername",
      key: "username",
   },
   {
      title: "Aktionen",
      key: "actions",
      className: "space-x-4",
      render(row) {
         let arr = []
         arr[0] = h(
            NButton,
            { 
               class: "invisible group-hover:visible align-middle",
               circle: true,
               onClick: () => { clickEdit(row.id) },
               renderIcon: () => { return renderIcon(Edit) },
            },
         )
         arr[1] = h(
            NButton,
            { 
               class: "invisible group-hover:visible align-middle",
               secondary: true,
               circle: true,
               type: "error",
               onClick: () => { clickDelete(row.id) },
               renderIcon: () => { return renderIcon(Delete) },
            },
         )
         return arr
      }
   }
]

function clickEdit(id){
   router.get('users/'+id+'/edit')
}

function clickDelete(id){
   console.log("Delete clicked: "+id)
}

function renderIcon(icon, className = "") {
   return h(NIcon, { component: icon, class: className, size: 20 })
}

</script>