'use client';

import { z } from 'zod';
import { zodResolver } from '@hookform/resolvers/zod';
import { useForm } from 'react-hook-form';
import Link from 'next/link';
import { signUp } from '@/lib/actions';
import { StatusMessage, SubmitButton } from '@/components/default';
import { useRouter } from 'next/navigation';
import { useAuth } from '@/components/context';
import {
	Card,
	CardContent,
	CardDescription,
	CardHeader,
	CardTitle,
	Form,
	FormControl,
	FormField,
	FormItem,
	FormLabel,
	FormMessage,
	Input,
	Separator,
} from '@/components/ui';
import { useEffect, useState } from 'react';
import {
	SignInWithApple,
	SignInWithMicrosoft,
} from '@/components/default/auth';

const formSchema = z
	.object({
		name: z.string().min(2, {
			message: 'Name must be at least 2 characters.',
		}),
		email: z.string().email({
			message: 'Please enter a valid email address.',
		}),
		password: z.string().min(8, {
			message: 'Password must be at least 8 characters.',
		}),
		confirmPassword: z.string().min(8, {
			message: 'Password must be at least 8 characters.',
		}),
	})
	.refine((data) => data.password === data.confirmPassword, {
		message: 'Passwords do not match!',
		path: ['confirmPassword'],
	});

const SignUp = () => {
	const router = useRouter();
	const { isAuthenticated, isLoading, refreshUserData } = useAuth();
	const [statusMessage, setStatusMessage] = useState('');

	const form = useForm<z.infer<typeof formSchema>>({
		resolver: zodResolver(formSchema),
		defaultValues: {
			name: '',
			email: '',
			password: '',
			confirmPassword: '',
		},
		mode: 'onChange',
	});

	// Redirect if already authenticated
	useEffect(() => {
		if (isAuthenticated) {
			router.push('/');
		}
	}, [isAuthenticated, router]);

	const handleSignUp = async (values: z.infer<typeof formSchema>) => {
		try {
			setStatusMessage('');
			const formData = new FormData();
			formData.append('name', values.name);
			formData.append('email', values.email);
			formData.append('password', values.password);
			const result = await signUp(formData);
			if (result?.success) {
				await refreshUserData();
				setStatusMessage(
					result.data ??
						'Thanks for signing up! Please check your email for a verification link.',
				);
				form.reset();
				router.push('');
			} else {
				setStatusMessage(`Error: ${result.error}`);
			}
		} catch (error) {
			setStatusMessage(
				`Error: ${error instanceof Error ? error.message : 'Could not sign in!'}`,
			);
		}
	};

	return (
		<Card className='min-w-xs md:min-w-sm'>
			<CardHeader>
				<CardTitle className='text-3xl font-medium'>Sign Up</CardTitle>
				<CardDescription className='text-foreground'>
					Already have an account?{' '}
					<Link className='text-primary font-medium underline' href='/sign-in'>
						Sign in
					</Link>
				</CardDescription>
			</CardHeader>
			<CardContent>
				<Form {...form}>
					<form
						onSubmit={form.handleSubmit(handleSignUp)}
						className='flex flex-col mx-auto space-y-4 mb-4'
					>
						<FormField
							control={form.control}
							name='name'
							render={({ field }) => (
								<FormItem>
									<FormLabel className='text-lg'>Name</FormLabel>
									<FormControl>
										<Input type='text' placeholder='Full Name' {...field} />
									</FormControl>
								</FormItem>
							)}
						/>
						<FormField
							control={form.control}
							name='email'
							render={({ field }) => (
								<FormItem>
									<FormLabel className='text-lg'>Email</FormLabel>
									<FormControl>
										<Input
											type='email'
											placeholder='you@example.com'
											{...field}
										/>
									</FormControl>
									<FormMessage />
								</FormItem>
							)}
						/>
						<FormField
							control={form.control}
							name='password'
							render={({ field }) => (
								<FormItem>
									<FormLabel className='text-lg'>Password</FormLabel>
									<FormControl>
										<Input
											type='password'
											placeholder='Your password'
											{...field}
										/>
									</FormControl>
									<FormMessage />
								</FormItem>
							)}
						/>
						<FormField
							control={form.control}
							name='confirmPassword'
							render={({ field }) => (
								<FormItem>
									<FormLabel className='text-lg'>Confirm Password</FormLabel>
									<FormControl>
										<Input
											type='password'
											placeholder='Confirm password'
											{...field}
										/>
									</FormControl>
									<FormMessage />
								</FormItem>
							)}
						/>
						{statusMessage &&
							(statusMessage.includes('Error') ||
							statusMessage.includes('error') ||
							statusMessage.includes('failed') ||
							statusMessage.includes('invalid') ? (
								<StatusMessage message={{ error: statusMessage }} />
							) : (
								<StatusMessage message={{ success: statusMessage }} />
							))}
						<SubmitButton
							className='text-[1.0rem] cursor-pointer'
							disabled={isLoading}
							pendingText='Signing Up...'
						>
							Sign Up
						</SubmitButton>
					</form>
				</Form>
				<div className='flex items-center w-full gap-4'>
					<Separator className='flex-1 bg-accent py-0.5' />
					<span className='text-sm text-muted-foreground'>or</span>
					<Separator className='flex-1 bg-accent py-0.5' />
				</div>
				<SignInWithMicrosoft type='signUp' />
				<SignInWithApple type='signUp' />
			</CardContent>
		</Card>
	);
};
export default SignUp;
