"use client";
import { CheckEmailCode } from "(app)/admin/user/action";
import { Check } from "lucide-react";
import { useSession } from "next-auth/react";
import { useRouter, useSearchParams } from "next/navigation";
import { useEffect, useState } from "react";
import toast from "react-hot-toast";

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

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

	async function verifyCode(code: string) {
		if (!session.data?.user.email || !code) return;
		const res = await CheckEmailCode(session.data?.user.id || "", code);
		if (res.error) {
		  toast.error(res.error);
		} else {
		  toast.success(res.message || "E-Mail erfolgreich bestätigt!");
		  router.push("/");
		}
	  }
	  
	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={!session.data?.user.email || !code}
					>
						Bestätigen
					</button>
				</div>
			</div>
		</div>
	);
}
