"use client";

import { useState } from "react";
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import { PageHeader } from "@/components/PageHeader";
import { PageFrame } from "@/components/PageFrame";
import { api, type CatalogueRow, type Term } from "@/lib/api";

const ENVS = ["sandbox", "production"] as const;

/* Self-hosted sells annual only, so the monthly cell is not rendered for it
 * rather than rendered and rejected. The backend refuses one either way; this is
 * so nobody types into a field that cannot be saved. */
function termsFor(deployment: string): Term[] {
    return deployment === "self_hosted" ? ["annual"] : ["monthly", "annual"];
}

function componentLabel(r: CatalogueRow): string {
    if (r.kind === "base") return "Base fee";
    if (r.kind === "limit") return `Per ${r.limit_key?.replace("max_", "")}`;
    return `Feature: ${r.feature_key}`;
}

function rowKey(r: CatalogueRow): string {
    return [r.deployment, r.tier, r.kind, r.limit_key ?? "", r.feature_key ?? ""].join("/");
}

export default function CataloguePage() {
    const qc = useQueryClient();
    const { data: rows = [], isLoading } = useQuery({
        queryKey: ["staff", "catalogue"],
        queryFn: api.staff.catalogue,
    });
    const [drafts, setDrafts] = useState<Record<string, CatalogueRow["price_ids"]>>({});

    const save = useMutation({
        mutationFn: (r: CatalogueRow) => api.staff.updateCatalogue(r),
        onSuccess: () => qc.invalidateQueries({ queryKey: ["staff", "catalogue"] }),
    });

    const groups = Array.from(new Set(rows.map((r) => `${r.deployment}/${r.tier}`)));

    return (
        <div className="grid gap-6">
            <PageHeader
                title="Catalogue"
                back={{ href: "/staff", label: "Operations" }}
                subtitle="Every priceable component. This is the only place a Paddle price ID lives."
            />
            <PageFrame
                aside={
                    <aside className="space-y-3 text-[0.82rem] text-ink-2">
                        <p>
                            A component with no price ID is free. A feature with no price is a
                            toggle a customer may take at no charge; giving it a price here is
                            all it takes to start charging for it.
                        </p>
                        <p>
                            Free is priced by nothing and has no rows. That absence is what
                            keeps it outside Paddle.
                        </p>
                        <p>
                            Changing a price affects the next checkout only. It cannot touch an
                            issued licence.
                        </p>
                    </aside>
                }
            >
                {isLoading ? (
                    <p className="text-[0.85rem] text-ink-3">Loading…</p>
                ) : (
                    <div className="space-y-6">
                        {groups.map((g) => {
                            const [deployment, tier] = g.split("/");
                            const terms = termsFor(deployment);
                            return (
                                <section key={g} className="space-y-2">
                                    <h2 className="text-[0.95rem] font-medium text-ink">
                                        {deployment === "cloud" ? "Cloud" : "Self-Hosted"}{" "}
                                        {tier}
                                    </h2>
                                    <div className="overflow-x-auto">
                                        <table className="w-full min-w-[42rem] border-collapse text-[0.82rem]">
                                            <thead>
                                                <tr className="border-b border-rule text-left text-ink-3">
                                                    <th className="py-2 pr-3 font-normal">Component</th>
                                                    {ENVS.map((env) =>
                                                        terms.map((t) => (
                                                            <th
                                                                key={`${env}-${t}`}
                                                                className="py-2 pr-3 font-normal"
                                                            >
                                                                {env} / {t}
                                                            </th>
                                                        )),
                                                    )}
                                                    <th className="py-2 font-normal" />
                                                </tr>
                                            </thead>
                                            <tbody>
                                                {rows
                                                    .filter(
                                                        (r) =>
                                                            r.deployment === deployment &&
                                                            r.tier === tier,
                                                    )
                                                    .map((r) => {
                                                        const k = rowKey(r);
                                                        const ids = drafts[k] ?? r.price_ids ?? {};
                                                        const dirty =
                                                            JSON.stringify(ids) !==
                                                            JSON.stringify(r.price_ids ?? {});
                                                        return (
                                                            <tr
                                                                key={k}
                                                                className="border-b border-rule/60"
                                                            >
                                                                <td className="py-2 pr-3 text-ink">
                                                                    {componentLabel(r)}
                                                                </td>
                                                                {ENVS.map((env) =>
                                                                    terms.map((t) => (
                                                                        <td
                                                                            key={`${env}-${t}`}
                                                                            className="py-2 pr-3"
                                                                        >
                                                                            <input
                                                                                value={
                                                                                    ids[env]?.[t] ?? ""
                                                                                }
                                                                                placeholder="pri_…"
                                                                                onChange={(e) =>
                                                                                    setDrafts({
                                                                                        ...drafts,
                                                                                        [k]: {
                                                                                            ...ids,
                                                                                            [env]: {
                                                                                                ...(ids[
                                                                                                    env
                                                                                                ] ?? {}),
                                                                                                [t]: e
                                                                                                    .target
                                                                                                    .value,
                                                                                            },
                                                                                        },
                                                                                    })
                                                                                }
                                                                                className="w-40 rounded border border-rule bg-panel px-2 py-1 font-mono text-[0.78rem] text-ink"
                                                                            />
                                                                        </td>
                                                                    )),
                                                                )}
                                                                <td className="py-2">
                                                                    <button
                                                                        type="button"
                                                                        disabled={
                                                                            !dirty || save.isPending
                                                                        }
                                                                        onClick={() =>
                                                                            save.mutate({
                                                                                ...r,
                                                                                price_ids: ids,
                                                                            })
                                                                        }
                                                                        className="rounded border border-accent/50 px-2.5 py-1 text-[0.78rem] text-accent disabled:opacity-40"
                                                                    >
                                                                        Save
                                                                    </button>
                                                                </td>
                                                            </tr>
                                                        );
                                                    })}
                                            </tbody>
                                        </table>
                                    </div>
                                </section>
                            );
                        })}
                    </div>
                )}
            </PageFrame>
        </div>
    );
}
