import { useMutation } from "@tanstack/react-query";
import { createFileRoute, Link, useNavigate } from "@tanstack/react-router";
import { useState } from "react";
import { toast } from "sonner";
import { Button } from "@/components/ui/button";
import {
	Card,
	CardContent,
	CardDescription,
	CardHeader,
	CardTitle,
} from "@/components/ui/card";
import { Input } from "@/components/ui/input";
import { authClient } from "@/lib/auth-client";

export const Route = createFileRoute("/reset-password")({
	validateSearch: (search: Record<string, unknown>) => {
		const token = typeof search.token === "string" ? search.token : undefined;
		return { ...(token !== undefined && { token }) } as { token?: string };
	},
	component: ResetPasswordPage,
});

function ResetPasswordPage() {
	const navigate = useNavigate();
	const search = Route.useSearch();
	const token = search.token;

	const [password, setPassword] = useState("");
	const [confirm, setConfirm] = useState("");

	const mutation = useMutation({
		mutationFn: async ({
			token,
			newPassword,
		}: {
			token: string;
			newPassword: string;
		}) => {
			const result = await authClient.resetPassword({ token, newPassword });
			if (result.error) {
				throw new Error(result.error.message);
			}
			return result.data;
		},
		onSuccess: () => {
			toast.success("Wachtwoord succesvol gewijzigd!");
			navigate({ to: "/login" });
		},
	});

	const handleSubmit = (e: React.FormEvent) => {
		e.preventDefault();
		if (password !== confirm) {
			toast.error("De wachtwoorden komen niet overeen.");
			return;
		}
		if (!token) {
			toast.error("Ongeldige reset-link. Vraag een nieuwe aan.");
			return;
		}
		mutation.mutate({ token, newPassword: password });
	};

	if (!token) {
		return (
			<div className="flex min-h-[calc(100dvh-2.75rem)] items-center justify-center px-4 sm:min-h-[calc(100dvh-3.5rem)]">
				<Card className="w-full max-w-md border-white/10 bg-white/5">
					<CardHeader className="text-center">
						<CardTitle className="font-['Intro',sans-serif] text-3xl text-white">
							Ongeldige link
						</CardTitle>
						<CardDescription className="text-white/60">
							Deze reset-link is ongeldig of verlopen.
						</CardDescription>
					</CardHeader>
					<CardContent className="text-center">
						<Link
							to="/forgot-password"
							className="text-sm text-white/60 hover:text-white"
						>
							Vraag een nieuwe reset-link aan
						</Link>
					</CardContent>
				</Card>
			</div>
		);
	}

	return (
		<div className="flex min-h-[calc(100dvh-2.75rem)] items-center justify-center overflow-y-auto px-4 py-8 sm:min-h-[calc(100dvh-3.5rem)]">
			<Card className="my-auto w-full max-w-md border-white/10 bg-white/5">
				<CardHeader className="text-center">
					<CardTitle className="font-['Intro',sans-serif] text-3xl text-white">
						Nieuw wachtwoord
					</CardTitle>
					<CardDescription className="text-white/60">
						Kies een nieuw wachtwoord voor je account
					</CardDescription>
				</CardHeader>
				<CardContent>
					<form onSubmit={handleSubmit} className="space-y-4">
						<div>
							<label
								htmlFor="password"
								className="mb-2 block text-sm text-white/60"
							>
								Nieuw wachtwoord
							</label>
							<Input
								id="password"
								type="password"
								placeholder="••••••••"
								value={password}
								onChange={(e) => setPassword(e.target.value)}
								required
								minLength={8}
								className="border-white/20 bg-white/10 text-white placeholder:text-white/40"
							/>
						</div>
						<div>
							<label
								htmlFor="confirm"
								className="mb-2 block text-sm text-white/60"
							>
								Bevestig wachtwoord
							</label>
							<Input
								id="confirm"
								type="password"
								placeholder="••••••••"
								value={confirm}
								onChange={(e) => setConfirm(e.target.value)}
								required
								minLength={8}
								className="border-white/20 bg-white/10 text-white placeholder:text-white/40"
							/>
						</div>
						{mutation.isError && (
							<p className="text-red-400 text-sm">{mutation.error.message}</p>
						)}
						<Button
							type="submit"
							disabled={mutation.isPending}
							className="w-full bg-white text-[#214e51] hover:bg-white/90"
						>
							{mutation.isPending ? "Bezig..." : "Stel wachtwoord in"}
						</Button>
					</form>
				</CardContent>
			</Card>
		</div>
	);
}
