"use client";

import { useEffect } from "react";
import { useRouter, useSearchParams } from "next/navigation";
import { useQueryClient } from "@tanstack/react-query";
import { LinkForm } from "./LinkForm";
import { PageHeader } from "@/components/PageHeader";

export default function LinkPage() {
    const router = useRouter();
    const qc = useQueryClient();
    // This page only claims a PAID placeholder's real install UUID. Self-hosted
    // Free is created on the purchase page, so with no placeholder to claim there
    // is nothing to do here send them there.
    const claimId = useSearchParams().get("claim") ?? undefined;

    useEffect(() => {
        if (!claimId) router.replace("/purchase");
    }, [claimId, router]);

    if (!claimId) return null;

    return (
        <div className="grid max-w-2xl gap-6">
            <PageHeader
                back={{ href: "/", label: "Overview" }}
                title="Link an install"
                subtitle="Every licence is tied to one install, so we need its ID before we can issue yours. Paste it below and your licence is ready on the next screen."
            />
            <LinkForm
                claimId={claimId}
                onLinked={(instanceId) => {
                    qc.invalidateQueries({ queryKey: ["account"] });
                    // Straight to the download, not back to a list: the licence is
                    // the thing they came for.
                    router.push(`/instances/${instanceId}`);
                }}
            />
        </div>
    );
}
