"use client";

import { zodResolver } from "@hookform/resolvers/zod";
import { Loader2 } from "lucide-react";
import Link from "next/link";
import { useRouter, useSearchParams } from "next/navigation";
import { signIn } from "next-auth/react";
import { useTransition } from "react";
import { type SubmitHandler, useForm } from "react-hook-form";
import { toast } from "sonner";
import { z } from "zod";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";

const OTPSchema = z.object({
	pin: z.string().min(6, {
		message: "Your one-time password must be 6 characters.",
	}),
});

export default function VerifyOTPForm({
	phone_number,
}: {
	phone_number: string;
}) {
	const [isPending, startTransition] = useTransition();
	const router = useRouter();
	console.log("verification in OTP form", phone_number);
	const {
		register,
		handleSubmit,
		formState: { errors },
	} = useForm<z.infer<typeof OTPSchema>>({
		defaultValues: {
			pin: "",
		},
		resolver: zodResolver(OTPSchema),
	});
	const searchParams = useSearchParams();
	const callbackUrl = searchParams.get("callbackUrl") || "/dashboard";

	const onSubmit: SubmitHandler<z.infer<typeof OTPSchema>> = (data) => {
		startTransition(async () => {
			const nextAuth = await signIn("credentials", {
				pin: data.pin,
				callbackUrl,
				redirect: false,
			});
			if (!nextAuth?.error) {
				router.push("/devices");
			} else {
				toast.error(JSON.parse(nextAuth?.error ?? "").message);
			}
		});
	};

	// "{\"message\":\"The token you entered isn't valid.\",\"status\":400}"

	return (
		<form
			onSubmit={handleSubmit(onSubmit)}
			className="w-full max-w-xs title-bg border-2 border-sarLinkOrange/50 rounded-lg shadow my-4"
		>
			<div className="grid pb-4 pt-4 gap-4 px-4">
				<div className="flex flex-col gap-4">
					<p className="text-center text-sm text-sarLinkOrange">
						Login OTP Sent to {phone_number}
					</p>
					<Label htmlFor="otp-number" className="sr-only text-gray-500">
						Enter the OTP
					</Label>
					<Input
						disabled={isPending}
						id="otp-number"
						{...register("pin")}
						type="text"
						placeholder="Enter OTP"
						className="bg-white dark:bg-black"
					/>
					{errors.pin && (
						<p className="text-red-500 text-sm">{errors.pin.message}</p>
					)}
				</div>
				<Button className="w-full" disabled={isPending} type="submit">
					{isPending ? <Loader2 className="animate-spin" /> : "Login"}
				</Button>
			</div>
			<div className="mb-4 text-center text-sm">
				Change{" "}
				<Link href="signin" className="underline">
					phone number
				</Link>
			</div>
		</form>
	);
}
