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

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

import { AiProviderProfileForm } from '~/components/settings/ai-provider-profile-form';
import { AppScreen } from '~/components/ui/app-screen';

const AiProviderFormRoute = () => {
  const router = useRouter();
  const { profileId: rawProfileId } = useLocalSearchParams<{
    profileId?: string;
  }>();
  const profileId = rawProfileId as Id<'aiProviderProfiles'> | undefined;
  const existing = useQuery(
    api.aiProviderProfiles.get,
    profileId ? { profileId } : 'skip',
  );
  const save = useAction(api.aiProviderProfilesNode.save);
  const updateMetadata = useMutation(api.aiProviderProfiles.updateMetadata);
  const [saving, setSaving] = useState(false);

  const submit = async (values: Parameters<typeof save>[0]) => {
    setSaving(true);
    try {
      if (profileId && !values.secret) {
        await updateMetadata({
          baseUrl: values.baseUrl,
          defaultModel: values.defaultModel,
          enabled: values.enabled,
          modelOptions: values.modelOptions,
          name: values.name,
          profileId,
          reasoningEffort: values.reasoningEffort,
        });
      } else {
        await save({ ...values, profileId });
      }
      router.replace('/settings/ai-providers');
    } catch (error) {
      console.error(error);
      Alert.alert('Could not save AI provider.');
    } finally {
      setSaving(false);
    }
  };

  if (profileId && !existing) {
    return (
      <AppScreen>
        <Stack.Screen options={{ title: 'Edit provider' }} />
        <Text className='text-muted-foreground'>Loading provider...</Text>
      </AppScreen>
    );
  }

  return (
    <AppScreen>
      <Stack.Screen
        options={{ title: profileId ? 'Edit provider' : 'New provider' }}
      />
      <Text className='text-foreground text-3xl font-bold'>
        {profileId ? 'Edit provider' : 'New provider'}
      </Text>
      <AiProviderProfileForm
        existing={existing ?? undefined}
        saving={saving}
        onSubmit={submit}
      />
    </AppScreen>
  );
};

export default AiProviderFormRoute;
