"use client";

import { useState } from "react";
import { ApiError, NotConnected, api } from "@/lib/api";
import { Button } from "@/components/Button";
import { Field } from "@/components/Field";

const UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;

export function LinkForm({
    onLinked,
    claimId,
}: {
    onLinked: (instanceId: string) => void;
    // The PAID placeholder awaiting its real install UUID: claim it in place. The
    // name was chosen at checkout, so it is not asked for again. Self-hosted Free
    // is created on the purchase page instead, not here.
    claimId: string;
}) {
    const [id, setId] = useState("");
    const [error, setError] = useState<string | undefined>();
    const [busy, setBusy] = useState(false);

    async function submit(e: React.FormEvent) {
        e.preventDefault();
        const value = id.trim();

        // Checked here so a typo costs nothing and the message is instant.
        if (!UUID_RE.test(value)) {
            setError(
                "That does not look like an instance ID. It should look like the example below.",
            );
            return;
        }

        setBusy(true);
        setError(undefined);
        try {
            const inst = await api.claimLink(claimId, value);
            onLinked(inst.instance_id);
        } catch (err) {
            setError(
                err instanceof NotConnected
                    ? "The licensing service is not reachable from this page."
                    : err instanceof ApiError
                      ? err.message
                      : "Could not link that instance. Try again.",
            );
        } finally {
            setBusy(false);
        }
    }

    return (
        <form onSubmit={submit} className="grid gap-4" noValidate>
            <Field
                label="Instance ID"
                value={id}
                onChange={(e) => setId(e.target.value)}
                error={error}
                hint={
                    <>
                        Find this on your install&rsquo;s <code>Settings → Licence</code> page, or on
                        the setup screen just after you first sign in. It looks like{" "}
                        <code>6a0fe3f0-49d2-4aa1-967c-a3094b200b5d</code>.
                    </>
                }
            />
            <Button type="submit" disabled={busy} className="justify-self-start">
                {busy ? "Linking…" : "Link and issue licence"}
            </Button>
        </form>
    );
}
