"use client";

import { useMutation } from "@tanstack/react-query";
import Link from "next/link";
import { useSearchParams } from "next/navigation";
import { Suspense, useState } from "react";
import { ApiError, api } from "@/lib/api";
import { Button } from "@/components/Button";
import { Field } from "@/components/Field";

function AcceptForm() {
    const token = useSearchParams().get("token") ?? "";
    const [password, setPassword] = useState("");
    const [error, setError] = useState<string | null>(null);
    const [done, setDone] = useState(false);

    const accept = useMutation({
        mutationFn: () => api.acceptInvite(token, password),
        onSuccess: () => setDone(true),
        onError: (e) =>
            setError(e instanceof ApiError ? e.message : "Something went wrong. Try again."),
    });

    if (!token) return <p className="text-ink-2">That link is missing its token.</p>;
    if (done)
        return (
            <div className="grid gap-3">
                <h1 className="text-3xl">You&apos;re in</h1>
                <p className="text-ink-2">Sign in with your email address and new password.</p>
                <Link href="/login" className="font-semibold text-accent underline">
                    Sign in
                </Link>
            </div>
        );

    return (
        <form
            className="grid max-w-md gap-4"
            onSubmit={(e) => {
                e.preventDefault();
                setError(null);
                accept.mutate();
            }}
        >
            <h1 className="text-3xl">Choose a password</h1>
            <p className="text-ink-2">
                This password signs you into Vantage HQ and into every instance you are given
                access to. Nobody who invited you can see it.
            </p>
            <Field
                label="New password"
                type="password"
                autoComplete="new-password"
                value={password}
                onChange={(e) => setPassword(e.target.value)}
                required
                minLength={12}
                hint="At least 12 characters."
                error={error ?? undefined}
            />
            <Button type="submit" disabled={accept.isPending || password.length < 12}>
                {accept.isPending ? "Setting…" : "Set password"}
            </Button>
        </form>
    );
}

export default function AcceptInvitePage() {
    return (
        <main className="mx-auto max-w-rail px-5 py-16">
            <Suspense fallback={<p className="text-ink-3">Loading…</p>}>
                <AcceptForm />
            </Suspense>
        </main>
    );
}
