<template>
  <v-dialog v-model="show" max-width="400">
    <v-card>
      <v-card-title class="headline">Iniciar sesión</v-card-title>
      <v-card-text>
        <v-form ref="form" @submit.prevent="onSubmit">
          <v-text-field
            v-model="username"
            label="Usuario"
            :rules="[required]"
            required
          />
          <v-text-field
            v-model="password"
            label="Contraseña"
            type="password"
            :rules="[required]"
            required
          />
          <v-alert v-if="error" type="error" class="mt-2">{{ error }}</v-alert>
        </v-form>
      </v-card-text>

      <v-card-actions>
        <v-spacer />
        <v-btn text @click="show = false">Cancelar</v-btn>
        <v-btn color="primary" @click="onSubmit">Entrar</v-btn>
      </v-card-actions>
    </v-card>
  </v-dialog>
</template>

<script>
import AuthService from '@/services/auth';

export default {
  name: 'LoginDialog',
  data: () => ({
    show: false,
    username: '',
    password: '',
    error: '',
  }),
  methods: {
    required(v) {
      return !!v || 'Campo obligatorio';
    },
    async onSubmit() {
      this.error = '';
      const form = this.$refs.form;
      if (!(await form.validate())) return;

      try {
        await AuthService.login({
          username: this.username,
          password: this.password,
        });
        this.show = false;
        this.$emit('login-success');
      } catch (e) {
        this.error = e.message ?? 'Error al iniciar sesión';
      }
    },
    open() {
      this.show = true;
    },
  },
};
</script>
