'use client';

import { useEffect, useRef, useState } from 'react';
import Link from 'next/link';
import { useMutation } from 'convex/react';

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

export const GitHubConnectClient = ({
  installationId,
}: {
  installationId?: string;
}) => {
  const connectInstallation = useMutation(api.github.connectInstallation);
  const [status, setStatus] = useState<'idle' | 'saving' | 'saved' | 'failed'>(
    installationId ? 'saving' : 'idle',
  );
  const hasSubmitted = useRef(false);

  useEffect(() => {
    if (!installationId || hasSubmitted.current) return;
    hasSubmitted.current = true;
    void connectInstallation({ installationId })
      .then(() => setStatus('saved'))
      .catch((error) => {
        console.error(error);
        setStatus('failed');
      });
  }, [connectInstallation, installationId]);

  return (
    <Card className='shadow-none'>
      <CardContent className='p-6'>
        <p className='text-lg font-medium'>GitHub App connection</p>
        <p className='text-muted-foreground mt-2'>
          {status === 'idle'
            ? 'GitHub did not provide an installation ID in this callback.'
            : status === 'saving'
              ? 'Saving your GitHub installation...'
              : status === 'saved'
                ? 'GitHub is connected. You can create forks from Spoon now.'
                : 'Could not save this GitHub installation.'}
        </p>
        <Button className='mt-5' asChild>
          <Link href='/spoons/new'>Create a Spoon</Link>
        </Button>
      </CardContent>
    </Card>
  );
};
