"use client"
import { useForm } from "react-hook-form";
import { z } from "zod";
import { zodResolver } from "@hookform/resolvers/zod";
import { toast } from "@/components/ui/use-toast";
import { Form, FormControl, FormField, FormItem, FormLabel, FormMessage } from "@/components/ui/form";
import { Input } from "@/components/ui/input";
import { Button } from "@/components/ui/button";
import { redirect } from "next/navigation";
import { loginSchema } from "./schema";
import { useRouter } from "next/navigation";
import { useSearchParams } from "next/navigation";
import revalidate from "./revalidate";
import { useState } from "react";
import Link from "next/link";

export default function LoginForm() {
	const router = useRouter()
	const searchParams = useSearchParams()
	const redirect = searchParams.get("from") ?? "/submission"
	const form = useForm<z.infer<typeof loginSchema>>({
		resolver: zodResolver(loginSchema),
	})
	const [submitted, setSubmitted] = useState(false)

	const onSubmit = form.handleSubmit(async (data, event) => {
		event.preventDefault()
		const res = await fetch('/api/auth/login', {
			method: 'POST',
			headers: {
				'Content-type': 'application/json',
			},
			body: JSON.stringify(data),
		})
		if (res.status === 200) {
			toast({ title: "login successful!" })
			setSubmitted(true)
			await revalidate(redirect)
			//BUG:the first time user logs in, page refreshes instead of redirecting
			router.push(redirect)
		} else {
			toast({ title: "login failed!" })
		}
	})


	return (
		<>
			{submitted ? <div className="flex flex-col items-center justify-around h-30 w-26">
				<h1>Logging in...</h1>
				<Button asChild>
					<Link href={redirect}>Continue</Link>
				</Button>
			</div> :
				<Form {...form}>
					<form onSubmit={onSubmit} className="mt-20 flex flex-col items-center space-y-6">
						<FormField
							control={form.control}
							name="email"
							render={({ field }) => (
								<FormItem>
									<FormLabel>Email Address</FormLabel>
									<FormControl>
										<Input placeholder="email goes here" {...field} />
									</FormControl>
									<FormMessage />
								</FormItem>
							)}
						></FormField>
						<FormField
							control={form.control}
							name="password"
							render={({ field }) => (
								<FormItem>
									<FormLabel>Password</FormLabel>
									<FormControl>
										<Input placeholder="password goes here" type="password"{...field} />
									</FormControl>
									<FormMessage />
								</FormItem>
							)}
						></FormField>
						<Button type="submit" className="mt-4">SUBMIT</Button>
					</form>
				</Form>
			}
		</>

	)
}

