import { Alert, Linking, Text, View } from 'react-native';

import { Badge } from '~/components/ui/badge';
import { Button } from '~/components/ui/button';
import { Card } from '~/components/ui/card';
import { EmptyState } from '~/components/ui/empty-state';

export const GitHubIntegrationPanel = ({
  connection,
  installUrl,
  loadingRepos,
  onListRepos,
  onSync,
  runtimeStatus,
  syncing,
}: {
  connection?: {
    displayName?: string;
    installationId?: string;
    status?: string;
  } | null;
  installUrl?: string | null;
  loadingRepos: boolean;
  onListRepos: () => Promise<string[]>;
  onSync: () => Promise<void>;
  runtimeStatus?: { encryptionConfigured?: boolean } | null;
  syncing: boolean;
}) => {
  const showRepos = async () => {
    try {
      const repos = await onListRepos();
      Alert.alert(
        'Accessible repositories',
        repos.slice(0, 20).join('\n') || 'No repositories returned.',
      );
    } catch (error) {
      console.error(error);
      Alert.alert('Could not list repositories.');
    }
  };

  const sync = async () => {
    try {
      await onSync();
      Alert.alert('GitHub synced', 'Installation metadata was refreshed.');
    } catch (error) {
      console.error(error);
      Alert.alert('Could not sync GitHub installation.');
    }
  };

  return (
    <>
      <Card className='gap-3'>
        <View className='flex-row items-center justify-between'>
          <Text className='text-foreground font-semibold'>GitHub App</Text>
          <Badge
            label={connection?.status ?? 'not connected'}
            tone={connection ? 'success' : 'warning'}
          />
        </View>
        {connection ? (
          <>
            <Text className='text-muted-foreground text-sm'>
              {connection.displayName}
            </Text>
            <Text className='text-muted-foreground text-xs'>
              Installation {connection.installationId ?? 'unknown'}
            </Text>
          </>
        ) : (
          <Text className='text-muted-foreground text-sm'>
            Connect GitHub so Spoon can create forks, compare branches, and open
            draft PRs.
          </Text>
        )}
        {installUrl ? (
          <Button onPress={() => void Linking.openURL(installUrl)}>
            Install or manage GitHub App
          </Button>
        ) : null}
        <Button
          disabled={syncing}
          variant='outline'
          onPress={() => void sync()}
        >
          {syncing ? 'Syncing...' : 'Sync installation'}
        </Button>
        <Button
          disabled={loadingRepos}
          variant='outline'
          onPress={() => void showRepos()}
        >
          {loadingRepos ? 'Loading...' : 'List repositories'}
        </Button>
      </Card>
      <Card>
        <Text className='text-foreground font-semibold'>Runtime status</Text>
        <Text className='text-muted-foreground mt-2 text-sm'>
          Encryption configured:{' '}
          {runtimeStatus?.encryptionConfigured ? 'yes' : 'not reported'}
        </Text>
      </Card>
      {!connection ? (
        <EmptyState
          description='Install the GitHub App, then sync the installation.'
          title='GitHub is not connected yet'
        />
      ) : null}
    </>
  );
};
