"use client";

import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { VerifyRegistrationOTP } from "@/queries/authentication";
import { Loader2 } from "lucide-react";
import Link from "next/link";
import { redirect, useSearchParams } from "next/navigation";
import { useActionState } from "react";

export default function VerifyRegistrationOTPForm({
	phone_number,
}: { phone_number: string }) {
	console.log("verification in OTP form", phone_number);

	const searchParams = useSearchParams();
	const mobile = searchParams.get("phone_number");
	if (!mobile) redirect("/auth/login");
	const [state, formAction, isPending] = useActionState(VerifyRegistrationOTP, {
		message: "",
		status: "",
	});

	return (
		<form
			action={formAction}
			className="w-full max-w-xs bg-white dark:bg-sarLinkOrange/10 title-bg border 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="bg-green-100 dark:bg-sarLinkOrange/50 border border-green-900/50 dark:border-sarLinkOrange/50 rounded p-2 text-center text-sm">
						Please enter the OTP sent to your mobile number [{phone_number}] to
						verify and complete your registration
					</p>
					<Label htmlFor="otp-number" className="sr-only text-gray-500">
						Enter the OTP
					</Label>
					<input
						type="number"
						name="mobile"
						defaultValue={phone_number}
						hidden
					/>
					<Input
						disabled={isPending}
						id="otp-number"
						name="otp"
						maxLength={6}
						type="number"
						placeholder="Enter OTP"
						className="bg-white text-black"
					/>
					{state?.status === "error" && (
						<p className="text-red-500 text-sm">{state.message}</p>
					)}
				</div>
				<Button className="w-full" disabled={isPending} type="submit">
					{isPending ? (
						<Loader2 className="animate-spin" />
					) : (
						"Request verification"
					)}
				</Button>
			</div>
			<div className="mb-4 text-center text-sm">
				Go back to{" "}
				<Link href="signin" className="underline">
					login
				</Link>
			</div>
		</form>
	);
}
