<!-- src/pages/auth/login.vue -->

<!-- Login.vue -->
<template>
  <div class="WrapperPlain">
    <div class="max-w-7xl mx-auto  ">
      <div class="mx-auto max-w-lg flex items-center justify-center  mt-4">
        <form
            class="rounded-md px-8 pt-6 pb-8 mb-4 w-full bg-neutral"
            @submit.prevent="onSubmit"
        >
          <div class="mb-4 text-center text-[28px] ">Login</div>
          <div class="mb-4">
            <label class="block text-white text-sm font-bold mb-2">Username</label>
            <input
                v-model="loginForm.username"
                :class="inputClasses(v$.loginForm.username, 'rounded w-full py-2 px-3 input-primary text-black')"
                id="username"
                type="text"
                placeholder="Username"
            />
          </div>
          <span
              v-if="v$.loginForm.username.$error"
              class="text-red-600 text-center"
          >
          {{ v$.loginForm.username.$errors[0].$message }}
        </span>

          <div class="">
            <label class="block text-white text-sm font-bold mb-2">
              Password
            </label>
            <input
                v-model="loginForm.password"
                :class="inputClasses(v$.loginForm.password, 'rounded w-full py-2 px-3 input-primary text-black')"
                id="password"
                type="password"
                autocomplete="off"
                placeholder="Password"
            />
            <span
                v-if="v$.loginForm.password.$error"
                class="text-red-600 text-center"
            >
            {{ v$.loginForm.password.$errors[0].$message }}
          </span>
          </div>

          <div class="flex items-center justify-center mb-6 mt-4">
            <button
                class="bg-primary hover:bg-zinc-400 text-white font-bold py-2 px-4 rounded focus:outline-none focus:shadow-outline"
                type="submit"
            >
              Sign In
            </button>
          </div>
          <div class="flex flex-col justify-center mt-5">
            <router-link
                :to="{ name: 'lostPassword' }"
                class="text-center font-bold text-sm text-white hover:text-accent"
            >Forgot Password?</router-link
            >
          </div>

          <div class="flex flex-col justify-center mt-5">
            <router-link
                :to="{ name: 'register' }"
                class="text-center font-bold text-sm text-white hover:text-accent"
            >Register Here</router-link
            >
          </div>
        </form>
      </div>
    </div>
  </div>

</template>

<script setup lang="ts">
import { ref, onMounted } from "vue";
import { useRouter } from "vue-router";
import { notify } from "@kyvg/vue3-notification";
import useValidate from "@vuelidate/core";
import { required, minLength } from "@vuelidate/validators";
import { useAuthStore } from "../../stores/auth";
import { authService } from "../../services/authService";
import { AxiosResponse, AxiosError } from "../../types/models";
import { useFormValidation } from "../../composables/useFormValidation";

const { inputClasses, validateForm } = useFormValidation();

// Stores & Utilities
const authStore = useAuthStore();
const router = useRouter();

// State
const loginForm = ref({
  username: "",
  password: "",
});

// Validation rules
const rules = {
  loginForm: {
    password: { required, minLength: minLength(6) },
    username: { required, minLength: minLength(6) },
  },
};

const v$ = useValidate(rules, { loginForm });

// Methods
const userStatus = async () => {
  try {
    const response: AxiosResponse<any> = await authService.whoami();
    if (response.data.ok) {
        authStore.setToken(response.data.user.token, response.data.user);
        router.push({ name: "home" });
    }
  } catch (error) {
    // Not logged in or error, stay on login page
  }
};

const sendLogin = async (payLoad: { username: string; password: string }) => {
  console.log("1. Attempting to send login request with payload:", payLoad);

  try {
    const response: AxiosResponse<any> = await authService.login(payLoad);
    console.log("2. Received response from API:", response);
    console.log("3. Raw response data from API:", response.data);

     if (response.data && response.data.user) {
        console.log("5. SUCCESS: Condition was true. User data found:", response.data.user);
        
        authStore.setToken(response.data.token, response.data.user);
        
        console.log("6. Token and user sent to Pinia store. Redirecting to home...");
        router.push({ name: "home" });

        notify({
          title: "Authorization",
          text: "You have been logged in!",
          type: "success",
        });

      } else {
        console.error("5. FAILURE: Condition was false. The 'response.data.user' object is missing or falsy.");
        
        if (response.data.locked) {
          notify({
            title: "Authorization",
            text: "Account has been locked for security reasons. Please unlock.",
            type: "error",
          });
          router.push({ name: "lostPassword" });
        } else {
          notify({
            title: "Authorization",
            text: "Login Failure! Check username or password.",
            type: "error",
          });
        }
      }
  } catch (err: unknown) {
      const error = err as AxiosError<any>;
      console.error("CRITICAL FAILURE: The API request failed entirely.", error);
      if (error.response) {
        // The request was made and the server responded with a status code
        // that falls out of the range of 2xx
        console.error("Error Response Data:", error.response.data);
        console.error("Error Response Status:", error.response.status);
      } else if (error.request) {
        // The request was made but no response was received
        console.error("No response received from the server. Is the backend running? Is the URL correct?", error.request);
      } else {
        // Something happened in setting up the request that triggered an Error
        console.error('Error setting up the request:', error.message);
      }

       // Handle specific error cases from authService if needed, standardizing on response.data.error if available
       const errorMsg = error.response?.data?.error || "A critical error occurred. Could not connect to the server.";

      notify({
        title: "Authorization",
        text: errorMsg,
        type: "error",
      });
  }
};

const onSubmit = async () => {
    const isFormCorrect = await v$.value.$validate();
    if (!isFormCorrect) {
    notify({
        title: "Authorization",
        text: "Form Error: Fields must be filled out correctly",
        type: "error",
    });
    } else {
    sendLogin(loginForm.value);
    }
};

onMounted(() => {
    userStatus();
});
</script>
