"use client";

import { useQuery } from "@tanstack/react-query";
import { useRouter, useSearchParams } from "next/navigation";
import Link from "next/link";
import { Suspense, useEffect } from "react";
import { api } from "@/lib/api";

function Verify() {
    const router = useRouter();
    const token = useSearchParams().get("token") ?? "";
    const { data, error, isLoading } = useQuery({
        queryKey: ["verify", token],
        queryFn: () => api.verify(token),
        enabled: token !== "",
        retry: false,
    });

    // An invitation and a verification link are the same shape, and someone will
    // paste one into the other. The backend leaves an invite token unspent and
    // says so; send them where they can actually finish.
    const needsPassword = data?.needs_password === true;
    useEffect(() => {
        if (needsPassword) {
            router.replace(`/accept-invite?token=${encodeURIComponent(token)}`);
        }
    }, [needsPassword, token, router]);
    if (needsPassword) return <Message title="One moment…" body="Taking you to set a password." />;

    if (!token)
        return (
            <Message
                title="That link is incomplete"
                body="It is missing its token. Use the link in the email exactly as sent."
            />
        );
    if (isLoading) return <Message title="Verifying…" body="One moment." />;
    if (error || !data?.verified)
        return (
            <Message
                title="That link is invalid or has expired"
                body="Links last 24 hours and can only be used once. Sign up again to get a fresh one."
            />
        );

    return (
        <div className="grid max-w-xl gap-3">
            <h1 className="text-3xl">Email verified</h1>
            <p className="text-ink-2">Your account is ready.</p>
            <Link href="/login" className="justify-self-start text-accent underline">
                Sign in
            </Link>
        </div>
    );
}

function Message({ title, body }: { title: string; body: string }) {
    return (
        <div className="grid max-w-xl gap-3">
            <h1 className="text-3xl">{title}</h1>
            <p className="text-ink-2">{body}</p>
        </div>
    );
}

export default function VerifyPage() {
    return (
        <main className="mx-auto max-w-rail px-5 py-12">
            <Suspense fallback={null}>
                <Verify />
            </Suspense>
        </main>
    );
}
