<template>
  <div class="mx-auto w-full max-w-lg">
          <span
              class="flex items-center justify-center bg-white text-xl font-bold uppercase text-primary-500 p-4"
          >
            LOGO
          </span>
      <form
      class="mt-8 space-y-6 rounded-lg border border-neutral-200 bg-white p-6 shadow-sm"
      @submit.prevent="handleSubmit"
    >
      <div>
        <label class="text-sm font-semibold text-neutral-700" for="user-select">
          Utilisateur
        </label>
        <select
          id="user-select"
          v-model="selectedUsername"
          class="mt-2 w-full rounded-md border border-neutral-300 bg-white px-3 py-2 text-base text-neutral-900 focus:border-primary-500 focus:outline-none focus:ring-2 focus:ring-primary-200"
          :disabled="isLoadingUsers"
        >
          <option value="" disabled>Choisir un utilisateur</option>
          <option v-for="user in users" :key="user.username" :value="user.username">
            {{ user.username }}
          </option>
        </select>
      </div>

      <div>
        <label class="text-sm font-semibold text-neutral-700" for="password">
          Mot de passe
        </label>
        <input
          id="password"
          v-model="password"
          type="password"
          autocomplete="current-password"
          class="mt-2 w-full rounded-md border border-neutral-300 bg-white px-3 py-2 text-base text-neutral-900 focus:border-primary-500 focus:outline-none focus:ring-2 focus:ring-primary-200"
        />
      </div>

      <button
        type="submit"
        class="w-full rounded-md bg-primary-500 px-4 py-2 text-base font-semibold text-white transition hover:bg-primary-600 disabled:cursor-not-allowed disabled:opacity-60"
        :disabled="isSubmitting"
      >
        Connexion
      </button>
          <p class="font-bold">v{{ version }}</p>
      </form>
  </div>
</template>

<script setup lang="ts">
import type { UserData } from '~/services/dto/user-data'
import { getUsers } from '~/services/auth'
import { useAuthStore } from '~/stores/auth'

const router = useRouter()
const auth = useAuthStore()
const { version } = useAppVersion()

definePageMeta({
  layout: 'auth'
})

const users = ref<UserData[]>([])
const isLoadingUsers = ref(true)
const selectedUsername = ref('')
const password = ref('')

const isSubmitting = computed(() => {
  return auth.isLoading || !selectedUsername.value || !password.value
})

const loadUsers = async () => {
  isLoadingUsers.value = true
  try {
    users.value = await getUsers()
  } finally {
    isLoadingUsers.value = false
  }
}

const handleSubmit = async () => {
  if (isSubmitting.value) {
    return
  }

  await auth.login(selectedUsername.value, password.value)
  await router.push('/')
}

onMounted(() => {
  void loadUsers()
})
</script>
