import { useEffect, useRef } from "react";
import { useAuth } from "react-oidc-context";
import { Navigate, Outlet, useLocation, useNavigate } from "react-router-dom";
import { clearStoredAdminAuthSession } from "../../lib/auth";

export default function AuthGuard() {
  const auth = useAuth();
  const location = useLocation();
  const navigate = useNavigate();
  const handledAuthErrorRef = useRef(false);
  const isTest =
    (window as Window & typeof globalThis & { _IS_TEST_MODE?: boolean })
      ._IS_TEST_MODE === true;

  useEffect(() => {
    if (!auth.error || handledAuthErrorRef.current || isTest) {
      return;
    }

    handledAuthErrorRef.current = true;
    clearStoredAdminAuthSession();
    void Promise.resolve(
      auth.removeUser ? auth.removeUser() : undefined,
    ).finally(() => {
      navigate("/login", { replace: true });
    });
  }, [auth, auth.error, isTest, navigate]);

  if (isTest) {
    return <Outlet />;
  }

  if (auth.isLoading || auth.activeNavigator) {
    return <div>Loading...</div>;
  }

  if (auth.error) {
    return (
      <div className="flex min-h-screen flex-col items-center justify-center p-4 text-center">
        <div className="mb-4 text-destructive">
          <h2 className="text-xl font-bold">인증 오류</h2>
          <p>{auth.error.message}</p>
        </div>
      </div>
    );
  }

  if (!auth.isAuthenticated) {
    const returnTo = `${location.pathname}${location.search}${location.hash}`;
    return (
      <Navigate
        to={`/login?returnTo=${encodeURIComponent(returnTo)}`}
        replace
      />
    );
  }

  return <Outlet />;
}
