'use client';

import Link from 'next/link';
import { useAction, useQuery } from 'convex/react';
import { makeFunctionReference } from 'convex/server';
import { Github, RefreshCw } from 'lucide-react';
import { toast } from 'sonner';

import { api } from '@spoon/backend/convex/_generated/api.js';
import { Button, Card, CardContent } from '@spoon/ui';

const syncConfiguredInstallationRef = makeFunctionReference<
  'action',
  Record<string, never>,
  string
>('githubNode:syncConfiguredInstallation');

export const GitHubConnectionPanel = () => {
  const connection = useQuery(api.github.getConnection, {});
  const installUrl = useQuery(api.github.getInstallUrl, {});
  const syncConfiguredInstallation = useAction(syncConfiguredInstallationRef);

  const handleSync = async () => {
    try {
      await syncConfiguredInstallation({});
      toast.success('GitHub installation connected.');
    } catch (error) {
      console.error(error);
      toast.error('Could not connect the configured GitHub installation.');
    }
  };

  return (
    <Card className='shadow-none'>
      <CardContent className='flex flex-col gap-4 p-5 md:flex-row md:items-center md:justify-between'>
        <div className='flex gap-3'>
          <div className='bg-primary/10 text-primary flex size-10 shrink-0 items-center justify-center rounded-lg'>
            <Github className='size-5' />
          </div>
          <div>
            <p className='font-medium'>GitHub App connection</p>
            <p className='text-muted-foreground mt-1 text-sm'>
              {connection
                ? `Connected to ${connection.displayName}`
                : 'Install or sync the Spoon GitHub App before creating forks.'}
            </p>
          </div>
        </div>
        <div className='flex flex-wrap gap-2'>
          {installUrl ? (
            <Button asChild variant='outline'>
              <Link href={installUrl}>Install GitHub App</Link>
            </Button>
          ) : null}
          <Button type='button' onClick={handleSync}>
            <RefreshCw className='size-4' />
            Sync configured installation
          </Button>
        </div>
      </CardContent>
    </Card>
  );
};
