import { Alert, Text, View } from 'react-native';
import { Link, Stack, useRouter } from 'expo-router';
import { useMutation, useQuery } from 'convex/react';

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

import { AppScreen } from '~/components/ui/app-screen';
import { Badge } from '~/components/ui/badge';
import { Button } from '~/components/ui/button';
import { EmptyState } from '~/components/ui/empty-state';
import { ListRow } from '~/components/ui/list-row';
import { titleize } from '~/utils/format';

const AiProvidersRoute = () => {
  const router = useRouter();
  const profiles = useQuery(api.aiProviderProfiles.listMine, {}) ?? [];
  const setDefault = useMutation(api.aiProviderProfiles.setDefault);
  const remove = useMutation(api.aiProviderProfiles.remove);

  return (
    <AppScreen>
      <Stack.Screen options={{ title: 'AI providers' }} />
      <View className='flex-row items-start justify-between gap-3'>
        <View className='min-w-0 flex-1'>
          <Text className='text-foreground text-3xl font-bold'>
            AI providers
          </Text>
          <Text className='text-muted-foreground mt-1'>
            Provider profiles for OpenCode workspaces.
          </Text>
        </View>
        <Link href='/settings/ai-provider-form' asChild>
          <Button>New</Button>
        </Link>
      </View>
      {profiles.length ? (
        profiles.map((profile) => (
          <ListRow
            key={profile._id}
            subtitle={`${titleize(profile.provider)} · ${profile.defaultModel}`}
            title={profile.name}
            onPress={() =>
              router.push(`/settings/ai-provider-form?profileId=${profile._id}`)
            }
          >
            <View className='flex-row flex-wrap gap-2'>
              <Badge
                label={profile.configured ? 'configured' : 'missing credential'}
                tone={profile.configured ? 'success' : 'warning'}
              />
              {profile.isDefault ? (
                <Badge label='default' tone='primary' />
              ) : null}
              <Badge label={profile.enabled ? 'enabled' : 'disabled'} />
            </View>
            <View className='mt-3 flex-row gap-2'>
              <Button
                disabled={!profile.configured || !profile.enabled}
                variant='outline'
                onPress={() => void setDefault({ profileId: profile._id })}
              >
                Set default
              </Button>
              <Button
                variant='danger'
                onPress={() =>
                  Alert.alert('Remove provider', `Remove ${profile.name}?`, [
                    { text: 'Cancel', style: 'cancel' },
                    {
                      text: 'Remove',
                      style: 'destructive',
                      onPress: () => void remove({ profileId: profile._id }),
                    },
                  ])
                }
              >
                Remove
              </Button>
            </View>
          </ListRow>
        ))
      ) : (
        <EmptyState
          description='Add an OpenAI, Codex/OpenCode, Anthropic, OpenRouter, or compatible provider before queueing agent work.'
          title='No AI providers'
        />
      )}
    </AppScreen>
  );
};

export default AiProvidersRoute;
