import { Pressable, Text, View } from 'react-native';
import { SafeAreaView } from 'react-native-safe-area-context';
import { Stack } from 'expo-router';
import { useAuthActions } from '@convex-dev/auth/react';
import { useConvexAuth, useQuery } from 'convex/react';

import { api } from '@gib/backend/convex/_generated/api.js';

const Index = () => {
  const { isAuthenticated, isLoading } = useConvexAuth();
  const { signOut } = useAuthActions();
  const user = useQuery(api.auth.getUser, isAuthenticated ? {} : 'skip');

  return (
    <SafeAreaView className='bg-background flex-1'>
      <Stack.Screen options={{ title: 'Home' }} />
      <View className='flex-1 items-center justify-center gap-4 p-6'>
        <Text className='text-foreground text-4xl font-bold'>
          Convex Monorepo
        </Text>
        <Text className='text-muted-foreground text-center text-base'>
          Your self-hosted Expo + Convex starter
        </Text>

        {isLoading ? (
          <Text className='text-muted-foreground'>Loading...</Text>
        ) : isAuthenticated ? (
          <View className='w-full gap-3'>
            <Text className='text-foreground text-center text-lg'>
              Welcome{user?.name ? `, ${user.name}` : ''}!
            </Text>
            <Pressable
              className='bg-primary items-center rounded-md p-3'
              onPress={() => void signOut()}
            >
              <Text className='text-primary-foreground font-semibold'>
                Sign Out
              </Text>
            </Pressable>
          </View>
        ) : (
          <View className='w-full gap-3'>
            <Text className='text-muted-foreground text-center'>
              Sign in to get started
            </Text>
            {/* Add sign-in UI here — see apps/next/src/app/(auth)/sign-in for patterns */}
          </View>
        )}
      </View>
    </SafeAreaView>
  );
};

export default Index;
