<script setup>
  const router = useRouter()
  const toast = useToast()

  const items = ref([])
  const pending = ref(true)

  const mapProfileRow = (user) => {
    const profile = user?.profile || {}

    return {
      id: profile?.id || null,
      employee_number: profile?.employee_number || '',
      full_name: profile?.full_name || user?.full_name || user?.email || 'Ohne Profil',
      email: user?.email || profile?.email || '',
      branch_name: profile?.branch?.name || '',
      team_names: (profile?.teams || []).map((team) => team?.name).filter(Boolean).join(', ')
    }
  }

  const setupPage = async () => {
    pending.value = true

    try {
      const response = await useNuxtApp().$api("/api/tenant/users")
      items.value = (response?.users || [])
        .map(mapProfileRow)
        .filter((item) => !!item.id)
    } catch (err) {
      console.error('[staff/profiles/index]', err)
      items.value = []
      toast.add({
        title: 'Profile konnten nicht geladen werden',
        color: 'error'
      })
    } finally {
      pending.value = false
    }
  }

  setupPage()

  const templateColumns = [
    {
      key: 'employee_number',
      label: "MA-Nummer",
    },{
      key: 'full_name',
      label: "Name",
    },{
      key: "email",
      label: "E-Mail",
    },{
      key: "branch_name",
      label: "Niederlassung",
    },{
      key: "team_names",
      label: "Teams",
    }
  ]
  const selectedColumns = ref(templateColumns)
  const columns = computed(() => templateColumns.filter((column) => selectedColumns.value.includes(column)))

</script>

<template>
  <UDashboardNavbar title="Benutzer Einstellungen">
      <template #right>
        <UButton
          @click="router.push(`/staff/profiles/create`)"
          disabled
        >
          + Mitarbeiter
        </UButton>
      </template>
  </UDashboardNavbar>
  <UTable
    :data="items"
    :columns="normalizeTableColumns(columns)"
    :loading="pending"
    :on-select="(row) => navigateTo(`/staff/profiles/${row.original?.id || row.id}`)"
  >
    <template #empty>
      <TableEmptyState label="Keine Mitarbeiterprofile gefunden" />
    </template>
  </UTable>
</template>

<style scoped>

</style>
