<template>
  <div class="login" v-if="store.authState == AuthState.UNAUTHORIZED">
    <div class="login-header">
      <img src="/icon-logo.svg" alt="logo" />
      <h1>Stacjownik Station Manager</h1>
    </div>

    <form @submit="signIn">
      <label for="name">Nick</label>
      <br />
      <input type="text" id="name" v-model="name" />
      <br />
      <label for="password">Hasło</label>
      <br />
      <input type="password" id="password" v-model="password" />
      <br />
      <button>{{ loginState == LoginState.LOADING ? 'Logowanie...' : 'Zaloguj się' }}</button>
    </form>
  </div>
</template>

<script lang="ts">
import axios from 'axios';
import { defineComponent } from 'vue';
import dataMixin from '../mixins/dataMixin';
import { useStore } from '../store';
import { AuthState, ILoginResponse } from '../types/types';

enum LoginState {
  INITIALIZED = 0,
  LOADING = 1,
  LOADED = 2,
}

export default defineComponent({
  mixins: [dataMixin],

  setup() {
    return {
      name: '',
      password: '',
      loginState: LoginState.INITIALIZED,
      LoginState,
      store: useStore(),
      AuthState,
    };
  },

  methods: {
    async signIn(e: Event) {
      e.preventDefault();
      this.loginState = LoginState.LOADING;

      try {
        const data: ILoginResponse = (
          await axios.post(
            `${this.API_URL}/auth/login`,
            { username: this.name, password: this.password },
            {
              headers: {
                'Content-Type': 'application/json',
              },
            }
          )
        ).data;

        this.store.authState = AuthState.AUTHORIZED;
        this.loginState = LoginState.LOADED;

        this.store.token = data.token;
        this.store.user = data.user;

        window.localStorage.setItem('auth-token', this.store.token);
        window.localStorage.setItem('user', JSON.stringify(this.store.user));

        this.loadData();
        this.$router.push('/');
      } catch (e: any) {
        this.store.authState = AuthState.UNAUTHORIZED;
        this.loginState = LoginState.LOADED;

        if (!e.response || e.response.status === undefined) {
          this.store.alertMessage = 'Wystąpił błąd podczas łączenia z serwerem!';
          return;
        }

        const response = e.response;
        const status: number = response.status;

        if (status == 401) {
          this.store.alertMessage = 'Nieprawidłowe dane!';
          return;
        }

        this.store.alertMessage = 'Wystąpił błąd podczas łączenia z serwerem!';
      }
    },
  },
});
</script>

<style lang="scss" scoped>
.login {
  display: flex;
  align-items: center;
  justify-content: center;

  flex-direction: column;
  height: 100vh;

  &-header {
    text-align: center;
  }
}

img {
  width: 8em;
}

input {
  font-size: 1.2rem;
  margin: 0.5rem 0;
  padding: 0.25em 0.3em;
  color: black;
}

h2 {
  text-align: center;
}

label {
  text-align: left;
}

button {
  width: 100%;
  margin: 1rem 0;
  padding: 0.5rem 0;
  font-size: 1rem;
}
</style>
