<script setup lang="ts">
import { VNodeRenderer } from '@layouts/components/VNodeRenderer'
import { themeConfig } from '@themeConfig'
import { useAuthStore } from '@/stores/useAuthStore'
import { useOrganisationStore } from '@/stores/useOrganisationStore'

definePage({
  meta: {
    layout: 'blank',
  },
})

const router = useRouter()
const route = useRoute()
const authStore = useAuthStore()
const orgStore = useOrganisationStore()

function selectOrganisation(orgId: string) {
  orgStore.setActiveOrganisation(orgId)
  const redirectTo = route.query.to ? String(route.query.to) : '/dashboard'
  router.replace(redirectTo)
}

// Auto-select if user has exactly one organisation
if (authStore.organisations.length === 1) {
  selectOrganisation(authStore.organisations[0].id)
}
</script>

<template>
  <div class="auth-wrapper bg-surface d-flex align-center justify-center" style="min-height: 100vh;">
    <VCard
      :max-width="500"
      class="pa-6"
      width="100%"
    >
      <VCardText class="text-center">
        <VNodeRenderer :nodes="themeConfig.app.logo" />
        <h4 class="text-h4 mt-4 mb-1">
          Kies je organisatie
        </h4>
        <p class="text-body-1 mb-0">
          Selecteer de organisatie waarmee je wilt werken.
        </p>
      </VCardText>

      <VCardText v-if="authStore.organisations.length === 0">
        <VAlert
          type="info"
          variant="tonal"
        >
          Je bent nog niet gekoppeld aan een organisatie. Neem contact op met je beheerder.
        </VAlert>
      </VCardText>

      <VCardText v-else>
        <VList>
          <VListItem
            v-for="org in authStore.organisations"
            :key="org.id"
            :title="org.name"
            :subtitle="org.role"
            rounded
            class="mb-2"
            @click="selectOrganisation(org.id)"
          >
            <template #prepend>
              <VAvatar
                color="primary"
                variant="tonal"
                size="40"
              >
                <span class="text-h6">{{ org.name.charAt(0).toUpperCase() }}</span>
              </VAvatar>
            </template>
            <template #append>
              <VIcon icon="tabler-chevron-right" />
            </template>
          </VListItem>
        </VList>
      </VCardText>
    </VCard>
  </div>
</template>
