import { useAuth } from "@/contexts/AuthContext";
import { Navigate } from "react-router-dom";
import { ReactNode, useEffect, useRef, useState } from "react";
import { isAdminUser } from "@/utils/adminCheck";

interface AdminProtectedRouteProps {
  children: ReactNode;
}

/**
 * Admin-specific route guard.
 * Uses the `user_roles` table (SSOT) via `isAdminUser` rather than the legacy
 * `profiles.role` field, which the user can write to and is therefore unsafe.
 */
export function AdminProtectedRoute({ children }: AdminProtectedRouteProps) {
  const { user, loading } = useAuth();
  const userId = user?.id ?? null;
  const [checking, setChecking] = useState(true);
  const [isAdmin, setIsAdmin] = useState(false);
  /** 已完成校验的用户，避免 TOKEN_REFRESH 等导致重复全屏 loading */
  const verifiedUserIdRef = useRef<string | null>(null);

  useEffect(() => {
    let cancelled = false;
    if (loading) return;
    if (!userId) {
      setChecking(false);
      setIsAdmin(false);
      verifiedUserIdRef.current = null;
      return;
    }

    const isNewUser = verifiedUserIdRef.current !== userId;
    if (isNewUser) {
      setChecking(true);
    }

    isAdminUser(userId).then((ok) => {
      if (cancelled) return;
      setIsAdmin(ok);
      setChecking(false);
      verifiedUserIdRef.current = ok ? userId : null;
    });
    return () => {
      cancelled = true;
    };
  }, [userId, loading]);

  if (loading || checking) {
    return (
      <div className="min-h-screen flex items-center justify-center bg-background">
        <div className="animate-spin rounded-full h-8 w-8 border-b-2 border-primary"></div>
      </div>
    );
  }

  if (!user || !isAdmin) {
    return <Navigate to="/admin/login" replace />;
  }

  return <>{children}</>;
}
