<template>
  <q-page padding class="login-page">
    <q-card flat class="login-card q-pa-lg bg-surface">
      <div class="text-center">
        <q-img src="images/kizzo_logo.svg" style="max-width: 220px" />
        <div
          class="text-weight-regular"
          style="font-size: 20px; letter-spacing: 0.15px"
        >
          Acesso do proprietário
        </div>
      </div>

      <q-form
        ref="loginForm"
        autocapitalize="off"
        autocomplete="off"
        autocorrect="off"
        class="q-pa-md"
        spellcheck="false"
        @submit="submitLogin"
      >
        <q-card-section class="q-mt-sm flex column q-gutter-y-md">
          <q-input
            v-model="email"
            hide-bottom-space
            label="Email"
            lazy-rules
            type="email"
            :rules="[inputRules.required, inputRules.email]"
          />

          <DefaultPasswordInput
            v-model="password"
            hide-bottom-space
            label="senha"
            :rules="[inputRules.required, inputRules.min(6)]"
          />
        </q-card-section>

        <q-card-actions align="right" class="q-px-md q-mt-md">
          <q-btn
            class="full-width"
            color="primary"
            label="Entrar"
            type="submit"
            size="md"
            style="border-radius: 8px"
            :loading="submitting"
          >
            <template #loading>
              <q-spinner />
            </template>
          </q-btn>
        </q-card-actions>
      </q-form>
    </q-card>
  </q-page>
</template>

<script setup>
import { onMounted, ref } from "vue";
import { useAuth } from "src/composables/useAuth";
import { useInputRules } from "src/composables/useInputRules";
import { useRouter } from "vue-router";

import DefaultPasswordInput from "src/components/defaults/DefaultPasswordInput.vue";

const router = useRouter();

const { inputRules } = useInputRules();

const email      = ref("");
const password   = ref(process.env.PASSWORD);
const submitting = ref(false);
const loginForm  = ref(null);

const submitLogin = async () => {
  try {
    submitting.value = true;

    const validate = await loginForm.value.validate();

    if (!validate) {
      return;
    }

    await useAuth().login(email.value, password.value);

    submitting.value = false;

    router.push({ name: "DashboardPage" });
  } catch (error) {
    submitting.value = false;
  }
};

onMounted(() => {
  if (process.env.DEV && process.env.SENHA) {
    password.value = process.env.SENHA;
  }
});
</script>

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

  .login-card {
    width:         100%;
    max-width:     600px;
    border-radius: 12px;
    padding-top:   40px;
  }
}
</style>
