"use client";

import { useQueries, useQuery } from "@tanstack/react-query";
import Link from "next/link";
import { API_BASE, NotConnected, api, type License } from "@/lib/api";
import { NotConnectedPanel } from "@/components/NotConnected";
import { InstanceCard } from "@/components/InstanceCard";

export default function OverviewPage() {
    const { data, error, isLoading } = useQuery({ queryKey: ["account"], queryFn: api.account });

    const licences = useQueries({
        queries: (data?.instances ?? [])
            .filter((i) => i.current_license)
            .map((i) => ({
                queryKey: ["license", i.instance_id],
                queryFn: () => api.license(i.instance_id),
            })),
    });

    if (error instanceof NotConnected) return <NotConnectedPanel url={API_BASE} />;
    if (isLoading || !data) return <p className="text-ink-3">Loading your account…</p>;

    const byInstance = new Map<string, License>();
    licences.forEach((q) => {
        if (q.data) byInstance.set(q.data.instance_id, q.data);
    });

    const unlinked = data.instances.filter((i) => i.status === "awaiting_link");

    return (
        <div className="grid gap-8">
            <header className="grid gap-2">
                <h1 className="text-3xl">{data.account.name}</h1>
                <p className="text-ink-2">{data.account.billing_email}</p>
            </header>

            {unlinked.length > 0 && (
                <div className="rounded border border-accent bg-accent-wash p-4">
                    <h2 className="text-xl">Finish setting up your licence</h2>
                    <p className="mt-1 text-[0.82rem] text-ink-2">
                        {unlinked.length === 1
                            ? "One purchase is"
                            : `${unlinked.length} purchases are`}{" "}
                        not attached to an install yet, so no licence has been issued for{" "}
                        {unlinked.length === 1 ? "it" : "them"}.
                    </p>
                    <Link
                        href="/instances/link"
                        className="mt-2 inline-block text-[0.82rem] font-semibold text-accent underline"
                    >
                        Link an install
                    </Link>
                </div>
            )}

            {data.instances.length === 0 ? (
                <div className="grid max-w-xl gap-3 rounded border border-rule bg-panel p-5">
                    <h2 className="text-xl">No instances yet</h2>
                    <p className="text-ink-2">
                        There are two ways to run Vantage. Buy a cloud instance and we host it, and
                        your licence is applied automatically. Or buy a self-hosted licence, install
                        Vantage on your own server, and link it here to get your licence file.
                    </p>
                </div>
            ) : (
                <section className="grid gap-4 sm:grid-cols-2 lg:grid-cols-3">
                    {data.instances.map((i) => (
                        <InstanceCard
                            key={i.instance_id}
                            instance={i}
                            license={byInstance.get(i.instance_id)}
                        />
                    ))}
                </section>
            )}
        </div>
    );
}
