<template>
  <q-page class="login-page" padding>
    <q-card class="login-card q-pa-lg bg-surface" flat>
      <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="isForgotPassword ? submitForgotPassword() : submitLogin()"
      >
        <q-card-section class="q-mt-sm flex column q-gutter-y-md">
          <q-banner
            v-if="isForgotPassword"
            class="bg-primary text-white"
            rounded
          >
            Informe seu email para receber o link de recuperação de senha.
          </q-banner>

          <q-input
            v-model="email"
            hide-bottom-space
            label="Email"
            lazy-rules
            type="email"
            :rules="[inputRules.required, inputRules.email]"
          />

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

          <div v-if="!isForgotPassword" class="text-right">
            <span
              class="text-primary cursor-pointer"
              style="font-size: 14px"
              @click="enableForgotPassword"
            >
              Trocar senha
            </span>
          </div>

          <div v-if="isForgotPassword" class="text-right">
            <span
              class="text-primary cursor-pointer"
              style="font-size: 14px"
              @click="cancelForgotPassword"
            >
              Voltar para login
            </span>
          </div>
        </q-card-section>

        <q-card-actions align="right" class="q-px-md q-mt-md">
          <q-btn
            class="full-width"
            color="primary"
            size="md"
            style="border-radius: 8px"
            type="submit"
            :label="isForgotPassword ? 'Enviar link' : 'Entrar'"
            :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 { sendForgotPasswordToken } from "src/api/forgotPassword";
import { useAuth } from "src/composables/useAuth";
import { useInputRules } from "src/composables/useInputRules";
import { useQuasar } from "quasar";
import { useRouter } from "vue-router";

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

const router = useRouter();

const $q = useQuasar();

const { inputRules } = useInputRules();

const email = ref("");

const password = ref(process.env.PASSWORD);

const submitting = ref(false);

const loginForm = ref(null);

const isForgotPassword = ref(false);

const enableForgotPassword = () => {
  isForgotPassword.value = true;
};

const cancelForgotPassword = () => {
  isForgotPassword.value = false;
};

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

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

    if (!validate) {
      submitting.value = false;
      return;
    }

    await sendForgotPasswordToken({
      email: email.value,
    });

    $q.notify({
      type: "positive",
      message: "Enviamos um link de recuperação para seu email.",
      position: "top-right",
      timeout: 5000,
    });

    isForgotPassword.value = false;

    submitting.value = false;
  } catch (error) {
    submitting.value = false;

    $q.notify({
      type: "negative",
      message:
        error?.response?.data?.message ||
        "Erro ao enviar email de recuperação.",
      position: "top-right",
      timeout: 5000,
    });
  }
};

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

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

    if (!validate) {
      submitting.value = false;

      return;
    }

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

    submitting.value = false;

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

    $q.notify({
      type: "negative",
      message:
        error?.response?.data?.message ||
        "Falha no login. Verifique suas credenciais.",
      position: "top-right",
      timeout: 5000,
    });
  }
};

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>
