import { useEffect, useState, type ReactNode } from "react";
import { AuthContext } from "./AuthContext";
import { useCookies } from 'react-cookie';

// BUG: The rerender issue is ridiclious, and needs to be updated. Maybe using a global
//      state management tool instead of a context
//
// BUG: We do not want to have access to these cookies in the UI, for security reasons. 
//      Instead, we should implement an api `/auth/status` can be requested to validate 
//      a token. Not sure how often this should get called, but it should be implemented.
export function AuthProvider({ children }: { children: ReactNode }) {
  const [cookies] = useCookies(["jwt_token"]);
  const [isLoggedIn, setIsLoggedIn] = useState<boolean | undefined>(cookies.jwt_token !== undefined);

  const getJwt = (): string => {
    if (!cookies.jwt_token) return "";
    return cookies.jwt_token as string;
  }

  useEffect(() => {
    setIsLoggedIn(cookies.jwt_token !== undefined);
  }, [cookies]);

  // NOTE: Display some loading page, maybe...
  // if (isLoggedIn === undefined) {
  //   return <div>Loading authentication...</div>; // or null for no flicker
  // }

  return (
    <AuthContext value={{ isLoggedIn, setIsLoggedIn, getJwt }}>
      {children}
    </AuthContext>
  );
}
