"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"
	console.log(redirect)
	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)
			router.refresh()
			router.push(redirect)
		} else {
			toast({ title: "login failed!" })
		}
	})


	return (
		<>
			{submitted ? <p>Logging in...</p> :
				<Form {...form}>
					<form onSubmit={onSubmit}>
						<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">SUBMIT</Button>
					</form>
				</Form>
			}
		</>

	)
}

