"use client";
import { checkEmailCode } from "(auth)/email-verification/action";
import { Check } from "lucide-react";
import { useRouter, useSearchParams } from "next/navigation";
import { useCallback, useEffect, useState } from "react";
import toast from "react-hot-toast";

export default function Page() {
	const router = useRouter();
	const searchParams = useSearchParams();
	const paramsCode = searchParams.get("code");
	const [code, setCode] = useState(paramsCode || "");

	const verifyCode = useCallback(
		async (code: string) => {
			if (!code) return;
			const res = await checkEmailCode(code);
			if (res.error) {
				console.log("Verification error:", res.error);
				toast.error(res.error);
			} else {
				toast.success(res.message || "E-Mail erfolgreich bestätigt!");
				router.push("/");
			}
		},
		[router],
	);

	useEffect(() => {
		if (!paramsCode) return;
		verifyCode(paramsCode);
	}, [paramsCode, verifyCode]);

	return (
		<div className="card bg-base-200 mb-4 shadow-xl">
			<div className="card-body">
				<p className="flex items-center gap-2 text-left text-2xl font-semibold">
					<Check className="h-5 w-5" /> E-Mail Bestätigung
				</p>
				<div className="flex w-full justify-center gap-3">
					<input
						className="input flex-1"
						placeholder="Bestätigungscode"
						value={code}
						onChange={(e) => setCode(e.target.value)}
					/>
					<button className="btn btn-primary" onClick={() => verifyCode(code)} disabled={!code}>
						Bestätigen
					</button>
				</div>
			</div>
		</div>
	);
}
