<script setup>
import { useAuthStore } from "@/stores/authStore";
import AuthProvider from "@/views/pages/authentication/AuthProvider.vue";
import authV1BottomShape from "@images/svg/auth-v1-bottom-shape.svg?url";
import authV1TopShape from "@images/svg/auth-v1-top-shape.svg?url";
import logomain from "@images/youngengineers/logomain.png";
import { storeToRefs } from "pinia";
import { showToast } from "@/composables/useStoreHelpers";
import { useField, useForm } from "vee-validate";
import { computed, onMounted, ref } from "vue";
import { useRoute, useRouter } from "vue-router";
import * as yup from "yup";

const router = useRouter();
const route = useRoute();

const auth = useAuthStore();
const { error, loading } = storeToRefs(auth);
const { login } = auth;

const isPasswordVisible = ref(false);

const validationSchema = yup.object({
  email: yup.string().required("Email is required").email("Invalid email"),
  password: yup.string().required("Password is required"),
  remember: yup.boolean(),
});

const { handleSubmit } = useForm({
  validationSchema,
});

const { value: email, errorMessage: emailError } = useField("email");
const { value: password, errorMessage: passwordError } = useField("password");
const { value: remember } = useField("remember");

const microsoftErrorCode = computed(() => {
  return route.query.microsoft_error ? String(route.query.microsoft_error) : "";
});

function getMicrosoftErrorMessage(code) {
  const messages = {
    init_failed: "Unable to start Microsoft login.",
    oauth_denied: "Microsoft login was cancelled or denied.",
    missing_authorization_code:
      "Microsoft did not return an authorization code.",
    missing_code_verifier: "Your login session expired. Please try again.",
    token_exchange_failed: "Unable to complete Microsoft sign in.",
    missing_access_token: "Microsoft access token was not returned.",
    email_not_provided: "No usable email address was returned by Microsoft.",
    user_not_found: "No account found for this Microsoft email.",
    account_not_linked: "This account is not linked properly.",
    account_disabled: "Account is disabled.",
    oauth_failed: "Microsoft login failed. Please try again.",
  };

  return messages[code] || "Microsoft login failed. Please try again.";
}

const onSubmit = handleSubmit(async (values) => {
  const normalizedValues = {
    ...values,
    email: values.email.toLowerCase().trim(),
  };

  const success = await login(normalizedValues);

  if (success) {
    router.replace(route.query.to ? String(route.query.to) : "/");
  }
});

function loginWithMicrosoft() {
  const target = route.query.to ? String(route.query.to) : "/";
  window.location.href = `/auth/microsoft/redirect?to=${encodeURIComponent(target)}`;
}

onMounted(() => {
  if (microsoftErrorCode.value) {
    const message = getMicrosoftErrorMessage(microsoftErrorCode.value);

    setTimeout(() => {
      showToast("error", "Microsoft Login Failed", message);
    }, 100);

    const cleanedQuery = { ...route.query };
    delete cleanedQuery.microsoft_error;

    router.replace({
      path: route.path,
      query: cleanedQuery,
    });
  }
});
</script>

<template>
  <div class="auth-wrapper d-flex align-center justify-center pa-4">
    <div class="position-relative my-sm-16">
      <VImg
        :src="authV1TopShape"
        class="text-primary auth-v1-top-shape auth-v1-shape d-none d-sm-block"
      />

      <VImg
        :src="authV1BottomShape"
        class="text-primary auth-v1-bottom-shape auth-v1-shape d-none d-sm-block"
      />

      <VCard
        class="auth-card"
        max-width="460"
        :class="$vuetify.display.smAndUp ? 'pa-6' : 'pa-0'"
      >
        <VCardItem class="justify-center">
          <RouterLink to="/" class="app-logo">
            <img
              :src="logomain"
              :height="$vuetify.display.xs ? '55' : '60'"
              class="d-flex"
            />
          </RouterLink>
        </VCardItem>

        <VCardText>
          <h4 class="text-h4 mb-1">Welcome to Youngengineers! 👋🏻</h4>
          <p class="mb-0">
            Please sign-in to your account and start the adventure
          </p>
        </VCardText>

        <VCardText>
          <VForm @submit.prevent="onSubmit">
            <VRow>
              <VCol cols="12">
                <VTextField
                  v-model="email"
                  label="Email"
                  type="email"
                  placeholder="johndoe@email.com"
                  :error-messages="emailError"
                />
              </VCol>

              <VCol cols="12">
                <VTextField
                  v-model="password"
                  label="Password"
                  placeholder="············"
                  :type="isPasswordVisible ? 'text' : 'password'"
                  autocomplete="current-password"
                  :append-inner-icon="isPasswordVisible ? 'bx-hide' : 'bx-show'"
                  @click:append-inner="isPasswordVisible = !isPasswordVisible"
                  :error-messages="passwordError"
                />

                <div
                  class="d-flex align-center justify-space-between flex-wrap my-6"
                >
                  <VCheckbox v-model="remember" label="Remember me" />

                  <RouterLink class="text-primary" to="/forgot-password">
                    Forgot Password?
                  </RouterLink>
                </div>

                <VBtn
                  :loading="loading"
                  :disabled="loading"
                  block
                  type="submit"
                >
                  Login
                </VBtn>

                <VCol cols="12" class="d-flex align-center">
                  <VDivider />
                  <span class="mx-4">or</span>
                  <VDivider />
                </VCol>

                <VBtn block @click="loginWithMicrosoft">
                  Login with Microsoft
                </VBtn>
              </VCol>

              <VCol cols="12" class="text-center">
                <AuthProvider />
              </VCol>
            </VRow>
          </VForm>
        </VCardText>
      </VCard>
    </div>
  </div>
</template>

<style lang="scss">
@use "@core-scss/template/pages/page-auth";
</style>
