import React, { useEffect } from "react";
import { useAuth, useUser } from "@clerk/clerk-react";
import { Navigate } from "react-router-dom";
import { useSupabaseWithClerk, ensureUserProfile } from "@/lib/supabase/auth";
import { Loader2 } from "lucide-react";

interface AuthGuardProps {
  children: React.ReactNode;
  redirectTo?: string;
}

export function AuthGuard({
  children,
  redirectTo = "/sign-in",
}: AuthGuardProps) {
  const { isLoaded, isSignedIn } = useAuth();
  const { user } = useUser();
  const { getAuthenticatedSupabase } = useSupabaseWithClerk();
  const [isProfileReady, setIsProfileReady] = React.useState(false);

  useEffect(() => {
    async function setupUserProfile() {
      if (!user) return;

      try {
        const { supabase } = await getAuthenticatedSupabase();

        // Supabase에 사용자 프로필 생성/업데이트
        await ensureUserProfile(supabase, user.id, {
          email: user.emailAddresses[0]?.emailAddress || "",
          username: user.username || undefined,
          firstName: user.firstName || undefined,
          lastName: user.lastName || undefined,
          profileImageUrl: user.imageUrl || undefined,
        });

        setIsProfileReady(true);
      } catch (error) {
        console.error("Error setting up user profile:", error);
        // 에러가 발생해도 일단 진행하도록 함
        setIsProfileReady(true);
      }
    }

    if (isSignedIn && user) {
      setupUserProfile();
    } else if (!isSignedIn && isLoaded) {
      setIsProfileReady(true);
    }
  }, [isSignedIn, user, getAuthenticatedSupabase, isLoaded]);

  // Clerk가 아직 로드되지 않았을 때
  if (!isLoaded || (isSignedIn && !isProfileReady)) {
    return (
      <div className="flex h-screen items-center justify-center">
        <div className="text-center">
          <Loader2 className="h-8 w-8 animate-spin mx-auto mb-4" />
          <p className="text-sm text-muted-foreground">Loading...</p>
        </div>
      </div>
    );
  }

  // 로그인되지 않았을 때
  if (!isSignedIn) {
    return <Navigate to={redirectTo} replace />;
  }

  // 로그인되었을 때
  return <>{children}</>;
}
