<script setup>
import { computed, reactive, ref } from 'vue'
import useVuelidate from '@vuelidate/core'
import { required } from '@vuelidate/validators'
import { useRouter } from 'vue-router'

import MessageBox from '@/components/MessageBox.vue'
import InputGroup from '@/components/InputGroup.vue'
import { MESSAGES } from '@/data/messages'
import { getTokenPayload, ResponseStatus } from '@/helpers'
import { auth as api } from '@/services/api'
import { useSessionStore } from '@/stores/session'

const props = defineProps(['msg'])

const message = ref(null)
const waiting = ref(false)

const router = useRouter()
const session = useSessionStore()

// Initial values
const state = reactive({
  emailOrUsername: null,
  password: null
})

const rules = computed(() => {
  return {
    emailOrUsername: { required },
    password: { required }
  }
})

const v$ = useVuelidate(rules, state)

async function onSubmit() {
  try {
    message.value = null

    const isValid = await v$.value.$validate()

    if (!isValid) {
      message.value = MESSAGES['INVALID_INPUT']

      return
    }

    const response = await api.login(state)

    if (response?.status === ResponseStatus.Success) {
      if (response.data?.token) {
        const payload = getTokenPayload(response.data?.token)

        session.setUser({ role: payload.role, userId: payload.userId }, true)

        if (payload.role === 'administrator') {
          waiting.value = true
          router.push({
            name: 'buildings'
          })
        } else if (payload.role === 'user') {
          waiting.value = true
          router.push({
            name: 'apartments'
          })
        }

        return
      }
    }

    message.value = MESSAGES[response.code]
    waiting.value = false
  } catch (error) {
    console.error('ERROR:', error.name)
  }
}
</script>

<template>
  <div class="form form-bg shadow">
    <form @submit.prevent="onSubmit">
      <div class="form-content">
        <InputGroup>
          <label for="login-username">E-Mail oder Benutzername</label>
          <input id="login-username" type="text" v-model="state.emailOrUsername" />
        </InputGroup>
        <InputGroup>
          <label for="login-password">Passwort</label>
          <input id="login-password" type="password" v-model="state.password" />
        </InputGroup>
      </div>
      <div class="form-section">
        <MessageBox v-if="message || props.msg" :msg="message || props.msg" :type="props.msg ? 'warning' : 'danger'" />
        <button class="button primary" type="submit" :disabled="waiting">
          <span v-if="!waiting">Anmelden</span>
          <font-awesome-icon v-else icon="fa-solid fa-spinner" />
        </button>
      </div>
    </form>
    <div class="section center">
      <router-link class="link" to="/reset-password">Password vergessen?</router-link>
    </div>
  </div>
</template>