"use client";
import { setUserAuthData } from "@/actions/cookies";
import MenuBar from "@/components/menu-bar";
import Navbar from "@/components/navbar";
import useCountDown from "@/hooks/useCountDown";
import Axios from "@/lib/Axios";
import useUserStore from "@/store/useUserStore";
import { UserDataT } from "@/types/auth";
import { useMutation } from "@tanstack/react-query";
import { ReactNode, useEffect } from "react";

type Resp = {
  access: string;
};

const Layout = ({ children }: { children: ReactNode }) => {
  const { setUserData, data: authData } = useUserStore();
  const { timer, startCountdown, tracker, completed, setCountDownValue } =
    useCountDown();

  const mutation = useMutation({
    mutationFn: refreshToken,
    onSuccess: (data, variables, context) => {
      const authDt = JSON.parse(JSON.stringify(authData)) as UserDataT;

      authDt!.tokens!.access = data;

      setUserAuthData(authDt);
      setUserData(authDt);
    },
  });

  async function refreshToken() {
    return Axios.post<Resp>("/core/token/refresh/", {
      refresh: authData?.tokens.refresh,
    }).then((res) => res.data.access);
  }

  function mutateToken() {
    if (tracker) return;

    mutation.mutate();
    const minuts = 60 * 9;

    setCountDownValue(minuts);
    startCountdown();
  }

  useEffect(() => {
    document.addEventListener("click", mutateToken);
    return () => document.removeEventListener("click", mutateToken);
  }, [authData, tracker]);

  return (
    <div className="">
      <Navbar />
      <MenuBar />
      <div className="px-10">{children}</div>
    </div>
  );
};

export default Layout;
