<script setup lang="ts">
import { ref, computed, watch, onMounted } from "vue";
import { PublicClientApplication } from "@azure/msal-browser";
import { useRouter } from "vue-router";
const router = useRouter();
import { Button } from "@/components/ui/button";
import {
  Card,
  CardContent,
  CardDescription,
  CardFooter,
  CardHeader,
  CardTitle,
} from "@/components/ui/card";
import { Input } from "@/components/ui/input";
import ToggleTheme from "@/components/common/ToggleTheme.vue";
import { Eye, EyeOff } from "lucide-vue-next";
import {
  trimUsernameToLimit,
  trimPasswordToLimit,
} from "@/type/util/loginValidator";

import { debounceWhitespace } from "@/type/util/debounce";
import { toast } from "vue-sonner";
import { useUserStore } from "@/store/userDetailStore";
const userStore = useUserStore();
import { decodeJWT } from "@/type/util/tokenDecoder";
import { getBoardList } from "@/api/endpoint-api";
import { useAuthStore } from "@/store/auth";
const authStore = useAuthStore();

import { useLimitStore } from "@/store/limitStore";
const limitStore = useLimitStore();
import { getLimiter } from "@/api/endpoint-api";

const username = ref("");
const password = ref("");
const debouncedUsername = ref("");
const errorMsg = ref("");
const trimmedUsername = computed(() =>
  trimUsernameToLimit(debouncedUsername.value.replace(/\s/g, "")),
);
const trimmedPassword = computed(() =>
  trimPasswordToLimit(password.value.replace(/\s/g, "")),
);

const updateUsername = debounceWhitespace((value: string) => {
  debouncedUsername.value = value;
}, 3000);

watch(username, (newValue) => {
  updateUsername(newValue);
});

async function logIn() {
  let responseObj;
  authStore.logout();
  try {
    const response = await authStore.login(
      trimmedUsername.value,
      trimmedPassword.value,
    );
    if (response) {
      const token = localStorage.getItem("access_token");
      if (token) {
        const user = decodeJWT(token);
        const boardsResponse = await getBoardList();
        if (user) {
          userStore.setUserDetails(
            user.oid,
            user.name,
            user.email,
            user.role,
            boardsResponse.ownedBoards,
            boardsResponse.collabBoards,
          );
          if (boardsResponse.ownedBoards.length === 1) {
            const boardId = boardsResponse.ownedBoards[0].id;
            router.push({ name: "Task Page", params: { id: boardId } });
          } else {
            await loadBoardList();
          }
        }
      }
    }
  } catch (error) {
    const responseError = error as any;
    responseObj = responseError.response.data;
    errorMsg.value = responseObj.message;
    if (responseObj) {
      toast.error(responseObj.message);
    } else {
      toast.error("Login failed");
    }
  }
}

const loadBoardList = async () => {
  if (authStore.isAuthenticated) limitStore.setLimit(await getLimiter());
  router.push("/board").then(() => {
    toast.success("Login successful");
  });
};

const pswdMode = ref("password");
const showPassword = () => {
  if (pswdMode.value === "password") {
    pswdMode.value = "text";
  } else {
    pswdMode.value = "password";
  }
};

const msalConfig = {
  auth: {
    clientId: "fc34cb9f-eb8a-4d8c-ae6c-33c4ef39867a",
    authority:
      "https://login.microsoftonline.com/79845616-9df0-43e0-8842-e300feb2642a",
    redirectUri: "http://localhost:5173/login",
  },
  cache: {
    cacheLocation: "sessionStorage",
    storeAuthStateInCookie: false,
  },
};

let msalInstance: PublicClientApplication | null = null;

onMounted(async () => {
  if (!msalInstance) {
    msalInstance = new PublicClientApplication(msalConfig);
    try {
      await msalInstance.initialize();
      console.log(msalInstance.getConfiguration());
      Promise.resolve().then(() => {
        msalInstance?.getConfiguration();
        msalInstance?.acquireTokenPopup({
          scopes: ["user.read"],
        });
        console.log("MSAL initialized successfully");
      });
    } catch (error) {
      console.error("Failed to initialize MSAL", error);
    }
  }

  if (authStore.isAuthenticated) {
    router.push("/board");
  }
});

const loginWithMicrosoft = async () => {
  if (!msalInstance) {
    console.error("MSAL instance not initialized");
    return;
  }

  if (msalInstance.getAllAccounts().length > 0) {
    console.warn("An interaction is already in progress. Please wait.");
    return;
  }

  try {
    const response = await msalInstance.loginPopup();
    console.log("Login successful", response);
    const token = response.accessToken;
    if (token) {
      const user = decodeJWT(token);
      const boardsResponse = await getBoardList();
      if (user) {
        userStore.setUserDetails(
          user.oid,
          user.name,
          user.email,
          user.role,
          boardsResponse.ownedBoards,
          boardsResponse.collabBoards,
        );
        if (boardsResponse.ownedBoards.length === 1) {
          const boardId = boardsResponse.ownedBoards[0].id;
          router.push({ name: "Task Page", params: { id: boardId } });
        } else {
          await loadBoardList();
        }
      }
    }
  } catch (error) {
    console.error("Login failed", error);
  }
};
</script>

<template>
  <div v-if="errorMsg !== ''" class="absolute hidden itbkk-message">
    {{ errorMsg }}
  </div>
  <div
    class="min-w-screen min-h-screen bg-gradient flex items-center justify-center content-center"
  >
    <div class="flex w-full max-w-screen-lg justify-center">
      <Card class="w-full max-w-sm pb-8">
        <CardHeader>
          <CardTitle class="text-2xl text-black">Hello,</CardTitle>
          <CardTitle class="text-2xl text-black">Welcome!</CardTitle>
          <CardDescription class="text-[#AEB4BB]">
            Login to your account.
          </CardDescription>
        </CardHeader>
        <CardContent class="grid gap-4">
          <div class="grid gap-2">
            <Input
              id="username"
              v-model="username"
              :value="trimmedUsername"
              type="username"
              placeholder="Username"
              required
              class="itbkk-username bg-[#EDECEC] border-none text-black focus:ring-0 placeholder:text-[#AEB4BB]"
            />
          </div>
          <div class="flex items-center rounded-md justify-end">
            <Input
              id="password"
              v-model="password"
              :value="trimmedPassword"
              :type="pswdMode"
              placeholder="Password"
              required
              class="itbkk-password border-none text-black focus:ring-0 placeholder:text-[#AEB4BB] bg-[#EDECEC] focus:outline-none focus:border-none"
            />
            <Eye
              v-if="pswdMode === 'password'"
              type="button"
              class="absolute text-[#AEB4BB] dark:text-[#AEB4BB] hover:text-[#b32854] dark:hover:text-[#334966] mr-2"
              @click="showPassword"
            />
            <EyeOff
              v-else
              type="button"
              class="absolute text-[#AEB4BB] dark:text-[#AEB4BB] hover:text-[#b32854] dark:hover:text-[#334966] mr-2"
              @click="showPassword"
            />
          </div>
        </CardContent>
        <CardFooter class="flex flex-col gap-4">
          <Button
            class="itbkk-button-signin w-full dark:bg-[#516E93] bg-[#D8517B] text-white hover:bg-[#b32854] dark:hover:bg-[#334966]"
            :class="{
              disabled: username.trim() === '' || password.trim() === '',
            }"
            :disabled="username.trim() === '' || password.trim() === ''"
            @click="logIn"
          >
            Sign in
          </Button>
          <Button
            class="itbkk-button-signin w-full dark:bg-[#09A7F0] bg-[#f37126] text-white hover:bg-[#b74b0c] dark:hover:bg-[#1d58c4]"
            @click="loginWithMicrosoft"
          >
            <img
              alt="Microsoft logo"
              src="https://upload.wikimedia.org/wikipedia/commons/thumb/4/44/Microsoft_logo.svg/512px-Microsoft_logo.svg.png?20210729021049"
              class="w-6 h-6 mr-2"
            />
            Sign in with Microsoft Account
          </Button>
        </CardFooter>
      </Card>
      <div
        class="w-full max-w-sm min-h-full dark:bg-gradient-to-bl dark:from-pink-500 dark:via-purple-500 dark:to-blue-400 bg-gradient-to-bl from-yellow-300 via-orange-400 to-red-300 flex justify-end items-end md:block"
      >
        <ToggleTheme class="min-w-fit max-w-fit m-1 hover:bg-transparent" />
      </div>
    </div>
  </div>
</template>

there is error: @azure_msal-browser.js?v=e221bc00:7975 Uncaught (in promise) BrowserAuthError: interaction_in_progress: Interaction is currently in progress. Please ensure that this interaction has been completed before calling an interactive API.   For more visit: aka.ms/msaljs/browser-errors