<script lang="ts" setup>
import {ref} from 'vue'
import {useRouter} from 'vue-router'
import {useSessionStore} from "@/stores/session.ts";


const sessionStore = useSessionStore()
const router = useRouter()

const username = ref('')
const password = ref('')
const loading = ref(false)
const error = ref('')

const rules = {
  required: (value: string) => !!value || 'Ce champ est requis.',
}

async function handleLogin() {
  loading.value = true
  error.value = ''

  try {
    await sessionStore.login(username.value, password.value)
    await router.push('/')
  } catch (err) {
    error.value = err instanceof Error ? err.message : 'Impossible de contacter le serveur'
  } finally {
    loading.value = false
  }
}
</script>

<template>
  <v-container class="fill-height" fluid>
    <v-row align="center" justify="center">
      <v-col cols="12" md="4" sm="8">
        <v-card class="elevation-12">
          <v-toolbar color="primary" dark flat>
            <v-toolbar-title>Connexion</v-toolbar-title>
          </v-toolbar>
          <v-card-text>
            <v-form @submit.prevent="handleLogin">
              <v-text-field
                v-model="username"
                :rules="[rules.required]"
                label="Nom d'utilisateur"
                name="username"
                prepend-icon="mdi-account"
                required
                type="text"
              />
              <v-text-field
                v-model="password"
                :rules="[rules.required]"
                label="Mot de passe"
                name="password"
                prepend-icon="mdi-lock"
                required
                type="password"
              />
              <v-alert v-if="error" class="mt-3" density="compact" type="error">
                {{ error }}
              </v-alert>
              <v-card-actions class="mt-4">
                <v-spacer/>
                <v-btn
                  :loading="loading"
                  block
                  color="primary"
                  size="large"
                  type="submit"
                >
                  Se connecter
                </v-btn>
              </v-card-actions>
              <div class="text-center mt-4">
                <router-link to="/auth/join">Pas encore de compte ? Rejoindre</router-link>
              </div>
            </v-form>
          </v-card-text>
        </v-card>
      </v-col>
    </v-row>
  </v-container>
</template>