'use client';

import * as React from 'react';
import { signIn } from 'next-auth/react';

import { cn } from '@/lib/utils';
import { Button, type ButtonProps } from '@/components/ui/Buttons';
import { IconGitHub, IconSpinner, IconGoogle } from '@/components/ui/Icon';

interface LoginButtonProps extends ButtonProps {
	oauth: 'github' | 'google';
}

export function LoginButton({ oauth, ...props }: LoginButtonProps) {
	const [isLoading, setIsLoading] = React.useState(false);

	const icon =
		oauth === 'github' ? (
			<IconGitHub className="mr-2" />
		) : (
			<IconGoogle className="mr-2" />
		);
	return (
		<Button
			variant="outline"
			onClick={() => {
				setIsLoading(true);
				// next-auth signIn() function doesn't work yet at Edge Runtime due to usage of BroadcastChannel
				signIn(oauth, { callbackUrl: `/` });
			}}
			disabled={isLoading}
			{...props}
		>
			{isLoading ? <IconSpinner className="mr-2 animate-spin" /> : icon}
			Sign in with {oauth.charAt(0).toUpperCase() + oauth.slice(1)}
		</Button>
	);
}
