'use client'

import {zodResolver} from '@hookform/resolvers/zod'
import {useState} from 'react'
import {useForm} from 'react-hook-form'
import {z} from 'zod'

import {login} from '@/actions/auth/login'
import CardWrapper from '@/components/auth/card-wrapper'
import {FormError} from '@/components/auth/form-error'
import GoogleLogin from '@/components/auth/google-login'
import {
	Form,
	FormControl,
	FormField,
	FormItem,
	FormLabel,
	FormMessage
} from '@/components/ui/form'
import {LoginSchema} from '@/lib/schemas'
import {Button} from '@/ui/button'
import {Input} from '@/ui/input'

export default function LoginForm() {
	const [loading, setLoading] = useState(false)
	const [error, setError] = useState('')

	const form = useForm<z.infer<typeof LoginSchema>>({
		resolver: zodResolver(LoginSchema),
		defaultValues: {
			email: '',
			password: ''
		}
	})

	const onSubmit = async (data: z.infer<typeof LoginSchema>) => {
		setLoading(true)
		login(data).then(res => {
			if (res?.error) {
				setError(res?.error)
				setLoading(false)
			} else {
				setError('')
				setLoading(false)
			}
		})
	}

	return (
		<CardWrapper
			headerLabel='Create an account'
			title='Register'
			backButtonHref='/auth/login'
			backButtonLabel='Already have an account'
			showSocial
		>
			<Form {...form}>
				<form
					onSubmit={form.handleSubmit(onSubmit)}
					className='m-auto space-y-6'
				>
					<div className='space-y-4'>
						<FormField
							control={form.control}
							name='email'
							render={({field}) => (
								<FormItem>
									<FormLabel>Email</FormLabel>
									<FormControl>
										<Input
											{...field}
											placeholder='johndoe@email.com'
											type='email'
										/>
									</FormControl>
									<FormMessage />
								</FormItem>
							)}
						/>

						<FormField
							control={form.control}
							name='password'
							render={({field}) => (
								<FormItem>
									<FormLabel>Password</FormLabel>
									<FormControl>
										<Input {...field} placeholder='******' type='password' />
									</FormControl>
									<FormMessage />
								</FormItem>
							)}
						/>
					</div>
					<FormError message={error} />
					<Button type='submit' className='w-full' disabled={loading}>
						{loading ? 'Loading...' : 'Login'}
					</Button>
				</form>
			</Form>
			<GoogleLogin />
		</CardWrapper>
	)
}
