import { ShieldHalf } from "lucide-react";
import { useEffect } from "react";
import { useAuth } from "react-oidc-context";
import { useNavigate } from "react-router-dom";
import { debugLog } from "../../lib/debugLog";

function AuthCallbackPage() {
  const auth = useAuth();
  const navigate = useNavigate();

  useEffect(() => {
    debugLog("[AuthCallbackPage] State:", {
      isAuthenticated: auth.isAuthenticated,
      isLoading: auth.isLoading,
      error: auth.error,
    });
    if (auth.isAuthenticated) {
      // Save token to localStorage for existing API clients that might still use it
      const user = auth.user;
      if (user?.access_token) {
        window.localStorage.setItem("admin_session", user.access_token);
      }
      const returnTo =
        typeof auth.user?.state === "object" &&
        auth.user?.state !== null &&
        "returnTo" in auth.user.state &&
        typeof auth.user.state.returnTo === "string"
          ? auth.user.state.returnTo
          : "/";
      console.info(
        "[AuthCallbackPage] Auth successful, navigating to",
        returnTo,
      );
      navigate(returnTo, { replace: true });
    } else if (auth.error) {
      console.error("[AuthCallbackPage] Auth Error:", auth.error);
      navigate("/login", { replace: true });
    }
  }, [auth.isAuthenticated, auth.error, navigate, auth.user, auth.isLoading]);

  return (
    <div className="flex min-h-screen items-center justify-center bg-background">
      <div className="flex flex-col items-center gap-4">
        <div className="flex h-16 w-16 items-center justify-center rounded-2xl bg-primary/15 text-primary shadow-lg animate-pulse">
          <ShieldHalf size={32} />
        </div>
        <div className="text-lg font-semibold">인증 완료 중...</div>
        <p className="text-sm text-muted-foreground">
          세션을 동기화하고 있습니다.
        </p>
      </div>
    </div>
  );
}

export default AuthCallbackPage;
