<template>
  <q-page class="login-page column items-center justify-center">
    <div class="login-overlay" />

    <div class="login-card column items-center">
      <div class="column items-center fields-card">
        <q-img :src="Logo" class="login-logo q-mb-lg" />

        <p class="login-subtitle">{{ $t("auth.select_type_hint") }}</p>

        <div class="type-tabs row q-mb-lg">
          <q-btn
            v-for="tipo in userTypes"
            :key="tipo.value"
            class="type-tab column items-center justify-center"
            :class="{ 'type-tab--active': selectedTipo === tipo.value }"
            @click="selectedTipo = tipo.value"
          >
            <div class="column items-center">
              <q-icon :name="tipo.icon" size="22px" />
              <span class="type-tab-label">{{ $t(tipo.label) }}</span>
            </div>
          </q-btn>
        </div>

        <q-form
          ref="formRef"
          class="full-width"
          autocorrect="off"
          autocapitalize="off"
          autocomplete="off"
          spellcheck="false"
          @submit="onSubmit"
        >
          <DefaultInput
            v-model="form.identifier"
            v-model:error="validationErrors.identifier"
            :type="isAssociado ? 'text' : 'email'"
            autofocus
            :label="isAssociado ? $t('auth.email_or_badge') : $t('common.terms.email')"
            :rules="isAssociado ? [inputRules.required] : [inputRules.required, inputRules.email]"
          >
            <template #append>
              <q-icon name="mdi-account-outline" color="grey-5" />
            </template>
          </DefaultInput>

          <DefaultPasswordInput
            v-model="form.password"
            v-model:error="validationErrors.password"
            :rules="[inputRules.required, inputRules.min(6)]"
            :label="$t('common.terms.password')"
          />

          <q-btn
            class="full-width q-mt-sm login-btn"
            color="violet-normal"
            :label="$t('auth.sign-in')"
            type="submit"
            unelevated
            :loading
          >
            <template #loading>
              <q-spinner />
            </template>
          </q-btn>
        </q-form>

        <div class="column items-center q-mt-md gap-xs">
          <router-link
            :to="{ name: 'ForgotPasswordPage', query: { tipo: selectedTipo } }"
            class="login-link"
          >
            {{ $t("auth.forgot_password") }}
          </router-link>
          <a href="/" class="login-link q-mt-xs">
            <q-icon name="mdi-arrow-left" size="12px" class="q-mr-xs" />
            {{ $t("auth.back_to_site") }}
          </a>
        </div>
      </div>
    </div>
  </q-page>
</template>

<script setup>
import { ref, computed, onBeforeMount, useTemplateRef } from "vue";
import { useQuasar } from "quasar";
import { useAuth } from "src/composables/useAuth";
import { useRouter } from "vue-router";
import { useInputRules } from "src/composables/useInputRules";
import { useSubmitHandler } from "src/composables/useSubmitHandler";
import { userStore } from "src/stores/user";

import Logo from "src/assets/logo_serprati.svg";
import DefaultInput from "src/components/defaults/DefaultInput.vue";
import DefaultPasswordInput from "src/components/defaults/DefaultPasswordInput.vue";

const router = useRouter();
const $q = useQuasar();
const { inputRules } = useInputRules();
const { login } = useAuth();
const store = userStore();

const formRef = useTemplateRef("formRef");
const selectedTipo = ref("administrador");
const isAssociado = computed(() => selectedTipo.value === "associado");

const userTypes = [
  { value: "associado",     label: "auth.type.associado",     icon: "mdi-account-outline" },
  { value: "administrador", label: "auth.type.administrador", icon: "mdi-shield-account-outline" },
  { value: "parceiro",      label: "auth.type.parceiro",      icon: "mdi-handshake-outline" },
];

const getRedirectByTipo = (tipo) => {
  if (tipo === "administrador") return { name: "DashboardPage" };
  if (tipo === "associado")     return { name: "CarteirinhaPage" };
  if (tipo === "parceiro")      return { name: "ParceiroHomePage" };
  return { name: "DashboardPage" };
};

const {
  loading,
  validationErrors,
  execute: submitForm,
} = useSubmitHandler({
  onSuccess: () => router.push(getRedirectByTipo(store.userTipo)),
  formRef,
});

const form = ref({
  identifier: null,
  password: process.env.PASSWORD ?? null,
});

const onSubmit = async () => {
  await submitForm(() => login(form.value.identifier, form.value.password, selectedTipo.value));
};

onBeforeMount(() => {
  const savedEmail = $q.cookies.get("email");
  if (savedEmail) {
    form.value.identifier = savedEmail;
  }
});
</script>

<style lang="scss" scoped>
@use "sass:map";
@use "src/css/quasar.variables.scss" as *;

.login-page {
  min-height: 100dvh;
  background-image: url("src/assets/pessoas_fundo.jpg");
  background-size: cover;
  background-position: center;
  position: relative;
}

.login-overlay {
  position: absolute;
  inset: 0;
  background: rgba(74, 20, 140, 0.48);
  z-index: 0;
}

.login-card {
  z-index: 1;
  display: flex;
  align-items: center;
  justify-content: center;
  width: calc(100% - 32px);
  min-height: calc(100dvh - 32px);
  background: rgba(255, 255, 255, 0.747);
  border-radius: 16px;
  box-shadow: 0 4px 32px rgba(0, 0, 0, 0.15);
}

.fields-card {
  width: 100%;
  max-width: 600px;
  padding: 32px;
  border-radius: 12px;
}

.login-logo {
  width: 380px;
}

.login-subtitle {
  color: map.get($colors, "violet-normal");
  font-size: 14px;
  font-weight: 500;
  margin: 0 0 24px;
  text-align: center;
}

.type-tabs {
  display: flex;
  gap: 10px;
  width: 100%;
}

.type-tab {
  flex: 1;
  min-width: 0;
  min-height: 72px;
  background: map.get($colors, "violet-light");
  border-radius: 10px;
  padding: 10px 4px;
  cursor: pointer;
  color: map.get($colors, "violet-normal");
  transition: border-color 0.2s, background 0.2s, color 0.2s;
  gap: 5px;

  &:hover {
    background: map.get($colors, "violet-light-hover");
  }

  &--active {
    background: map.get($colors, "violet-normal");
    color: #fff;
    box-shadow: 0 2px 10px rgba(102, 29, 117, 0.35);
  }
  &--active:hover {
    background: map.get($colors, "violet-normal-hover");
    box-shadow: 0 4px 20px rgba(102, 29, 117, 0.5);
  }
}

.type-tab-label {
  font-size: 12px;
  font-weight: 500;
}

.login-btn {
  height: 44px;
  font-size: 15px;
  font-weight: 600;
  letter-spacing: 0.5px;
}

.login-link {
  color: map.get($colors, "violet-normal");
  font-size: 13px;
  text-decoration: none;
  cursor: pointer;

  &:hover {
    color: map.get($colors, "violet-hover");
    text-decoration: underline;
  }
}


</style>
