<template>
  <q-layout>
    <q-page-container>
      <q-page class="flex bg-image flex-center">
        <q-card
          v-bind:style="$q.screen.lt.sm ? { width: '80%' } : { width: '30%' }">
          <q-card-section>
            <q-img
              fit="scale-down"
              src="~assets/oysqn_logo.png" />
          </q-card-section>
          <q-card-section>
            <div class="text-center q-pt-sm">
              <div class="col text-h6">Log in</div>
            </div>
          </q-card-section>
          <q-form @keydown.enter.prevent="doTokenLogin">
            <q-card-section class="q-gutter-md">
              <q-input
                v-model="email"
                label="E-Mail"
                type="email"
                color="darkblue"
                filled></q-input>
              <q-input
                v-if="userId"
                v-model="token"
                label="6-digit code"
                type="number"
                color="darkblue"
                filled></q-input>
            </q-card-section>
          </q-form>
          <q-card-section class="q-pa-none">
            <div class="row justify-center q-ma-sm">
              <q-btn
                type="button"
                @click="doTokenLogin"
                color="primary"
                label="Login with E-mail"
                style="width: 300px" />
            </div>
            <div class="row justify-center q-ma-sm">
              <GoogleOauthComponent />
            </div>
            <div class="row justify-center q-ma-sm">
              <DiscordOauthComponent />
            </div>
            <div class="row justify-center">
              <q-btn
                flat
                color="secondary"
                to="/pwreset"
                label="Forgot Password?" />
            </div>
          </q-card-section>
        </q-card>
      </q-page>
    </q-page-container>
  </q-layout>
</template>

<style>
.bg-image {
  background-image: url('/src/assets/oys_lighthouse.jpg');
  background-repeat: no-repeat;
  background-position-x: center;
  background-size: cover;
  /* background-image: linear-gradient(
    135deg,
    #ed232a 0%,
    #ffffff 75%,
    #14539a 100%
  ); */
}
</style>

<script setup lang="ts">
import { ref } from 'vue';
import GoogleOauthComponent from 'src/components/GoogleOauthComponent.vue';
import DiscordOauthComponent from 'src/components/DiscordOauthComponent.vue';
import { Dialog, Notify } from 'quasar';
import { useAuthStore } from 'src/stores/auth';
import { useRouter } from 'vue-router';
import { AppwriteException } from 'appwrite';
import { APP_VERSION } from 'src/version.js';

const email = ref('');
const token = ref('');
const userId = ref();
const router = useRouter();

console.log('version:' + APP_VERSION);

const doTokenLogin = async () => {
  const authStore = useAuthStore();
  if (!userId.value) {
    try {
      const sessionToken = await authStore.createTokenSession(email.value);
      userId.value = sessionToken.userId;
      Dialog.create({ message: 'Check your e-mail for your login code.' });
    } catch (e) {
      Dialog.create({
        message: 'An error occurred.  Please ask for help in Discord',
      });
    }
  } else {
    const notification = Notify.create({
      type: 'primary',
      position: 'top',
      spinner: true,
      message: 'Logging you in...',
      timeout: 8000,
      group: false,
    });
    try {
      await authStore.tokenLogin(userId.value, token.value);
      notification({
        type: 'positive',
        message: 'Logged in!',
        timeout: 2000,
        spinner: false,
        icon: 'check_circle',
      });
      router.replace({ name: 'index' });
    } catch (error: unknown) {
      if (error instanceof AppwriteException) {
        if (error.type === 'user_session_already_exists') {
          useRouter().replace({ name: 'index' });
          notification({
            type: 'positive',
            message: 'Already Logged in!',
            timeout: 2000,
            spinner: false,
            icon: 'check_circle',
          });
          return;
        }
        Dialog.create({
          title: 'Login Error!',
          message: error.message,
          persistent: true,
        });
      }
      notification({
        type: 'negative',
        message: 'Login failed.',
        timeout: 2000,
      });
    }
  }
};
</script>
