import { Alert, Text } from 'react-native';
import { Link, Stack } from 'expo-router';
import { useAuthActions } from '@convex-dev/auth/react';
import { useQuery } from 'convex/react';

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

import { AppScreen } from '~/components/ui/app-screen';
import { Button } from '~/components/ui/button';
import { ListRow } from '~/components/ui/list-row';

const SettingsRoute = () => {
  const { signOut } = useAuthActions();
  const user = useQuery(api.auth.getUser, {});
  const connection = useQuery(api.github.getConnection, {});
  const providers = useQuery(api.aiProviderProfiles.listMine, {}) ?? [];
  const defaultProvider = providers.find((provider) => provider.isDefault);

  return (
    <AppScreen>
      <Stack.Screen options={{ title: 'Settings' }} />
      <Text className='text-foreground text-3xl font-bold'>Settings</Text>
      <Link href='/settings/profile' asChild>
        <ListRow
          subtitle={
            user?.email ?? 'Name, email, provider, and password settings'
          }
          title='Profile'
        />
      </Link>
      <Link href='/settings/integrations' asChild>
        <ListRow
          subtitle={
            connection
              ? `GitHub connected as ${connection.displayName}`
              : 'GitHub App connection and accessible repositories'
          }
          title='Integrations'
        />
      </Link>
      <Link href='/settings/ai-providers' asChild>
        <ListRow
          subtitle={
            defaultProvider
              ? `${providers.length} provider${providers.length === 1 ? '' : 's'}, default ${defaultProvider.name}`
              : 'OpenCode, Codex auth, API keys, and default models'
          }
          title='AI providers'
        />
      </Link>
      <Button
        variant='danger'
        onPress={() =>
          Alert.alert('Sign out', 'Sign out of Spoon on this device?', [
            { text: 'Cancel', style: 'cancel' },
            {
              text: 'Sign out',
              style: 'destructive',
              onPress: () => void signOut(),
            },
          ])
        }
      >
        Sign out
      </Button>
    </AppScreen>
  );
};

export default SettingsRoute;
