"use client";
import { useAuth } from "react-oidc-context";
import { useState, useEffect } from "react";
import { useRouter, usePathname } from "next/navigation";
import { Source_Sans_3, Nunito } from "next/font/google";

const nunito = Nunito({
  subsets: ["latin"],
});

export default function AuthStatus() {
  const auth = useAuth();
  const router = useRouter();
  const pathname = usePathname();
  const [persistentAuthState, setPersistentAuthState] = useState<{
    isAuthenticated: boolean;
    user: any;
    hasInitialized: boolean;
  }>({
    isAuthenticated: false,
    user: null,
    hasInitialized: false,
  });

  useEffect(() => {
    // Only update persistent state when we have a definitive auth state
    if (!auth.isLoading && !auth.error) {
      setPersistentAuthState({
        isAuthenticated: auth.isAuthenticated,
        user: auth.user,
        hasInitialized: true,
      });
    }
  }, [auth.isLoading, auth.isAuthenticated, auth.user, auth.error]);

  useEffect(() => {
    // Redirect to / if user is definitely not logged in and not already on /
    if (
      persistentAuthState.hasInitialized &&
      !persistentAuthState.isAuthenticated &&
      pathname !== "/"
    ) {
      router.push("/");
    }
  }, [
    persistentAuthState.hasInitialized,
    persistentAuthState.isAuthenticated,
    pathname,
    router,
  ]);

  // Show loading only on first load, not on subsequent navigations
  if (!persistentAuthState.hasInitialized && auth.isLoading) {
    return (
      <div
        className={`${nunito.className} absolute top-4 right-4 rounded-lg bg-white/10 px-3 py-2 backdrop-blur-sm`}
      >
        <span className="text-sm">...</span>
      </div>
    );
  }

  const displayState = persistentAuthState.hasInitialized
    ? persistentAuthState
    : { isAuthenticated: auth.isAuthenticated, user: auth.user };

  return (
    displayState.isAuthenticated && (
      <div
        className={`${nunito.className} absolute top-4 right-4 flex items-center gap-2 rounded-lg bg-blue-950/80 px-3 py-2`}
      >
        <div className="h-2 w-2 rounded-full bg-green-500"></div>
        <span className="text-sm font-medium text-white">
          {displayState.user?.profile.name || "Authenticated"}
        </span>
        <button
          onClick={() => {
            void auth.removeUser();
            router.push("/");
          }}
          className="ml-1 rounded bg-gray-500/50 px-2 py-1 text-xs transition-colors hover:bg-red-500/30"
        >
          Uitloggen
        </button>
      </div>
    )
  );
}
