import React, { useEffect, useState } from 'react';
import { Stack } from 'expo-router';
import { useAuthWithProfile } from '~/lib/hooks/useAuthWithProfile';
import { router, usePathname } from 'expo-router';
import { AuthService } from '~/lib/services/authServices';

export default function AuthLayout() {
  const { user, loading, profile, profileLoading } = useAuthWithProfile();
  const pathname = usePathname();
  const [checkingAgent, setCheckingAgent] = useState(false);

  // Redirect to agent signin if no user and not on an auth page
  useEffect(() => {
    if (!loading && !user) {
      // If not on any auth page, redirect to agent signin
      const authPages = ['/auth/signin', '/auth/phone-setup', '/auth/google-setup', '/auth/otp', '/auth/forgot', '/auth/agent-signin'];
      const isOnAuthPage = authPages.some(page => pathname?.includes(page));
      
      if (!isOnAuthPage) {
        console.log('Auth Layout - no user, redirecting to agent signin');
        router.replace('/auth/agent-signin');
        return;
      }
    }
  }, [user, loading, pathname]);

  // Redirect to home if user is authenticated AND has a complete profile OR is an agent
  useEffect(() => {
    console.log('Auth Layout - user:', user?.uid, 'loading:', loading, 'profile:', !!profile, 'profileLoading:', profileLoading, 'pathname:', pathname);

    // Setup pages that should not redirect even if user has profile
    const setupPages = ['/auth/phone-setup', '/auth/google-setup', '/auth/agent-signin'];
    const isOnSetupPage = setupPages.some(page => pathname.includes(page));

    // Skip if still loading or on setup page
    if (loading || profileLoading || checkingAgent || isOnSetupPage || !user) {
      return;
    }

    const checkAndRedirect = async () => {
      // Check if user has a complete profile (regular user)
      if (profile && profile.fullName && (profile.phoneNumber || profile.email)) {
        console.log('Auth Layout - user has complete profile, redirecting to home');
        router.replace('/');
        return;
      }

      // Check if user is an agent (exists in agents collection)
      setCheckingAgent(true);
      try {
        const isAgent = await AuthService.checkAgentExists(user.uid);
        if (isAgent) {
          console.log('Auth Layout - user is an agent, redirecting to home');
          router.replace('/');
        }
      } catch (error) {
        console.error('Auth Layout - error checking agent:', error);
      } finally {
        setCheckingAgent(false);
      }
    };

    checkAndRedirect();
  }, [user, loading, profile, profileLoading, pathname, checkingAgent]);

  return (
    <Stack
      screenOptions={{
        headerShown: false,
      }}
    >
      <Stack.Screen name="signin" />
      <Stack.Screen name="phone-setup" />
      <Stack.Screen name="google-setup" />
      <Stack.Screen name="otp" />
      <Stack.Screen name="forgot" />
      <Stack.Screen name="agent-signin" />
    </Stack>
  );
}
