<template>
  <div class="login">
    <h2>Login</h2>
    <form @submit.prevent="runLogin">
      <label for="email">Email-Adresse:</label>
      <input type="email" id="email" v-model="email" required>

      <label for="password">Passwort:</label>
      <input type="password" id="password" v-model="password" required>

      <button type="submit">Login</button>
    </form>
    <p>
      <router-link to="/register">Registrieren</router-link>
    </p>
    <p>
      <router-link to="/forgot-password">Passwort vergessen?</router-link>
    </p>
    <DialogComponent 
      :title="dialogTitle" 
      :message="dialogMessage"  
      v-model="dialogVisible" 
      @close="closeDialog" 
    />
  </div>
</template>

<script>
import axios from '../../axios';
import DialogComponent from '../../common/components/DialogComponent.vue';
import { mapActions } from 'vuex';

export default {
  name: 'LoginComponent',
  components: {
    DialogComponent
  },
  data() {
    return {
      email: '',
      password: '',
      dialogTitle: '',
      dialogMessage: '',
      dialogVisible: false
    };
  },
  methods: {
    ...mapActions(['login']),
    async runLogin() {
      try {
        const response = await axios.post('/auth/login', {
          email: this.email,
          password: this.password
        });
        const token = response.data.token;
        const user = response.data.user;
        this.login({ user, token });
        axios.defaults.headers.common['Authorization'] = `Bearer ${token}`;
        this.$router.push('/admin/index');
      } catch (error) {
        if (error.response) {
          this.showDialog('Fehler', error.response.data.message);
        } else {
          this.showDialog('Ein Fehler ist aufgetreten', error.message);
        }
      }
    },
    showDialog(title, message) {
      this.dialogTitle = title;
      this.dialogMessage = message;
      this.dialogVisible = true;
    },
    closeDialog() {
      this.dialogVisible = false;
    }
  }
};
</script>

<style scoped>
.login {
  max-width: 400px;
  margin: auto;
}

form {
  display: flex;
  flex-direction: column;
}

label {
  margin-top: 10px;
}

button {
  margin-top: 20px;
}
</style>
