"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) => {
			console.log("Verifying code:", code);
			if (!code) return;
			const res = await checkEmailCode(code);
			console.log("Verification response:", res);
			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 shadow-xl mb-4 ">
			<div className="card-body">
				<p className="text-2xl font-semibold text-left flex items-center gap-2">
					<Check className="w-5 h-5" /> E-Mail Bestätigung
				</p>
				<div className="flex justify-center gap-3 w-full">
					<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>
	);
}
