'use client'; import React, { useState } from 'react'; import { Paper, TextInput, PasswordInput, Button, Stack, Text, Divider, Group, Anchor, Checkbox, Alert, Title, Container, } from '@mantine/core'; import { useForm } from '@mantine/form'; import { IconAlertCircle, IconBrandGoogle, IconBrandGithub } from '@tabler/icons-react'; import { SignInProps, SignInFormData } from './SignIn.types'; import { useAuth } from '../../hooks/useAuth'; import { useRouter } from 'next/navigation'; export function SignIn({ redirectUrl = '/dashboard', afterSignInUrl, providers = ['email', 'google', 'github'], appearance, onSuccess, onError, rememberMe = true, showDivider = true, forgotPasswordUrl = '/forgot-password', signUpUrl = '/sign-up', initialEmail = '', className, style, }: SignInProps) { const router = useRouter(); const { signIn, signInWithGoogle, signInWithGithub } = useAuth(); const [loading, setLoading] = useState(false); const [error, setError] = useState(null); const form = useForm({ initialValues: { email: initialEmail, password: '', rememberMe: false, }, validate: { email: (value) => (!value ? 'Email is required' : !/^\S+@\S+$/.test(value) ? 'Invalid email' : null), password: (value) => (!value ? 'Password is required' : value.length < 6 ? 'Password must be at least 6 characters' : null), }, }); const handleSubmit = async (values: SignInFormData) => { setLoading(true); setError(null); try { const user = await signIn(values.email, values.password, values.rememberMe); if (onSuccess) { onSuccess(user); } const redirectTo = afterSignInUrl || redirectUrl; router.push(redirectTo); } catch (err: any) { const errorMessage = err.message || 'Failed to sign in'; setError(errorMessage); if (onError) { onError(err); } } finally { setLoading(false); } }; const handleSocialSignIn = async (provider: 'google' | 'github') => { setLoading(true); setError(null); try { let user; if (provider === 'google') { user = await signInWithGoogle(); } else { user = await signInWithGithub(); } if (onSuccess) { onSuccess(user); } const redirectTo = afterSignInUrl || redirectUrl; router.push(redirectTo); } catch (err: any) { const errorMessage = err.message || `Failed to sign in with ${provider}`; setError(errorMessage); if (onError) { onError(err); } } finally { setLoading(false); } }; const socialButtons = providers.includes('google') || providers.includes('github') ? ( {providers.includes('google') && ( )} {providers.includes('github') && ( )} ) : null; const showSocialTop = appearance?.layout?.socialButtonsPlacement === 'top'; return ( Welcome back Sign in to your account to continue {error && ( } color="red" mb="md"> {error} )} {showSocialTop && socialButtons} {showSocialTop && showDivider && providers.includes('email') && ( )} {providers.includes('email') && (
{rememberMe && ( )} Forgot password?
)} {!showSocialTop && showDivider && socialButtons && providers.includes('email') && ( )} {!showSocialTop && socialButtons} Don't have an account?{' '} Sign up
); }