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

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

import { GitHubIntegrationPanel } from '~/components/settings/github-integration-panel';
import { AppScreen } from '~/components/ui/app-screen';

const IntegrationsRoute = () => {
  const installUrl = useQuery(api.github.getInstallUrl, {});
  const connection = useQuery(api.github.getConnection, {});
  const status = useQuery(api.integrations.getStatus, {});
  const syncInstallation = useAction(api.githubNode.syncConfiguredInstallation);
  const repositories = useAction(api.githubNode.listInstallationRepositories);
  const [syncing, setSyncing] = useState(false);
  const [loadingRepos, setLoadingRepos] = useState(false);

  const sync = async () => {
    setSyncing(true);
    try {
      await syncInstallation({});
    } finally {
      setSyncing(false);
    }
  };

  const listRepos = async () => {
    setLoadingRepos(true);
    try {
      const result = await repositories({});
      return result.map((repo) => repo.fullName);
    } finally {
      setLoadingRepos(false);
    }
  };

  return (
    <AppScreen onRefresh={() => void sync()} refreshing={syncing}>
      <Stack.Screen options={{ title: 'Integrations' }} />
      <Text className='text-foreground text-3xl font-bold'>Integrations</Text>
      <GitHubIntegrationPanel
        connection={connection}
        installUrl={installUrl}
        loadingRepos={loadingRepos}
        runtimeStatus={status}
        syncing={syncing}
        onListRepos={listRepos}
        onSync={sync}
      />
    </AppScreen>
  );
};

export default IntegrationsRoute;
