<template>
  <main class="min-h-screen flex items-center justify-center bg-gradient-to-br from-blue-50 to-indigo-100 p-6">
    <div class="w-full max-w-md">
      <div class="card bg-base-100 shadow-2xl">
        <div class="card-body">
          <h1 class="text-2xl font-bold mb-6 text-center">
            Connexion
          </h1>

          <div v-if="loadingProfiles" class="flex justify-center py-8">
            <span class="loading loading-spinner loading-lg" />
          </div>

          <form v-else @submit.prevent="handleLogin">
            <div class="form-control mb-4">
              <label class="label">
                <span class="label-text">Profil</span>
              </label>
              <select
                v-model="selectedProfileId"
                class="select select-bordered w-full"
                required
              >
                <option value="" disabled>
                  Choisir un profil...
                </option>
                <option
                  v-for="profile in profiles"
                  :key="profile.id"
                  :value="profile.id"
                >
                  {{ profile.firstName }} {{ profile.lastName }}
                </option>
              </select>
            </div>

            <div class="form-control mb-2">
              <label class="label">
                <span class="label-text">Mot de passe</span>
              </label>
              <input
                ref="passwordInput"
                v-model="password"
                type="password"
                placeholder="Mot de passe"
                class="input input-bordered w-full"
                :class="{ 'input-error': loginError }"
              >
            </div>

            <p v-if="loginError" class="text-error text-sm mb-4">
              {{ loginError }}
            </p>

            <button
              type="submit"
              class="btn btn-primary w-full mt-4"
              :disabled="!selectedProfileId || submitting"
            >
              <span v-if="submitting" class="loading loading-spinner loading-xs" />
              Se connecter
            </button>
          </form>

          <footer v-if="activeProfile" class="mt-6 pt-4 border-t border-base-300 flex justify-between items-center">
            <div class="text-sm text-base-content/70">
              Connecte :
              <span class="font-semibold">{{ activeProfile.firstName }} {{ activeProfile.lastName }}</span>
            </div>
            <button type="button" class="btn btn-outline btn-sm" @click="handleLogout">
              Deconnexion
            </button>
          </footer>
        </div>
      </div>
    </div>
  </main>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { useProfiles, useProfileSession } from '#imports'

const router = useRouter()
const { profiles, loadingProfiles, fetchProfiles } = useProfiles()
const { activeProfile, activateProfile, fetchCurrentProfile, logout } = useProfileSession()

const selectedProfileId = ref('')
const password = ref('')
const loginError = ref('')
const submitting = ref(false)
const passwordInput = ref(null)

const handleLogin = async () => {
  if (!selectedProfileId.value) { return }
  submitting.value = true
  loginError.value = ''
  try {
    await activateProfile(selectedProfileId.value, password.value || undefined)
    await router.push('/')
  } catch (error) {
    const err = error
    if (err?.status === 401 || err?.statusCode === 401) {
      loginError.value = 'Mot de passe incorrect.'
    } else {
      loginError.value = 'Erreur lors de la connexion.'
    }
  } finally {
    submitting.value = false
  }
}

const handleLogout = async () => {
  await logout()
  selectedProfileId.value = ''
  password.value = ''
}

onMounted(async () => {
  await fetchProfiles()
  await fetchCurrentProfile()
})
</script>
