<template>
  <form class="box" @submit.prevent="doAction">
    <b-field label="E-Mail-Adresse">
      <b-input type="email" v-model="user.email" />
    </b-field>
    <b-field label="Kennwort">
      <b-input type="password" v-model="user.password" />
    </b-field>

    <div v-if="false" class="notification is-danger">
      Email or password was wrong.
    </div>

    <div class="buttons">
      <b-button
        native-type="submit"
        type="is-primary"
        style="margin-left: auto; margin-right: 0; order: 10"
      >
        {{ mode === "login" ? "Anmelden" : "Konto anlegen" }}
      </b-button>
    </div>
  </form>
</template>

<script lang="ts">
import { Component, Prop, Vue, Watch } from "vue-property-decorator";
import { User } from "@/api";
import { Route } from "vue-router";

@Component
export default class LoginForm extends Vue {
  @Prop() private user!: User;

  private mode: "login" | "signup" = "login";

  public created(): void {
    if (this.$route.name === "signup") this.mode = "signup";
  }

  @Watch("$route")
  public routeChanged(to: Route): void {
    if (to.name === "signup") {
      this.mode = "signup";
    } else {
      this.mode = "login";
    }
  }

  private async doAction() {
    if (this.mode === "login") {
      await this.user.login();
    } else {
      await this.user.signup();
    }
    // TODO: error handling, show confirmation page
  }
}
</script>
