"use client";

import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import { useState } from "react";
import { api, type Deployment, type Plan, type Tier } from "@/lib/api";
import { ConfirmPlanChange } from "@/components/ConfirmPlanChange";
import { PageHeader } from "@/components/PageHeader";

const SUPPORT_LEVELS = [
    { value: "community", label: "Community" },
    { value: "email_24_5", label: "Email, 24/5" },
    { value: "email_call_24_7", label: "Email + call, 24/7" },
] as const;

const LIMIT_FIELDS = [
    { key: "max_servers", label: "Servers" },
    { key: "max_monitors", label: "Monitors" },
    { key: "max_secret_groups", label: "Secret groups" },
    { key: "max_channels", label: "Channels" },
    { key: "audit_retention_days", label: "Audit history (days)" },
] as const;

/*
 * -1 is Unlimited everywhere in the licence payload, so the form takes it
 * literally rather than inventing a checkbox. A staff screen that hides the
 * sentinel is a staff screen where nobody can tell whether a plan says
 * unlimited or nothing at all.
 */
function AllowanceForm({ plan, onSave, saving }: { plan: Plan; onSave: (next: Plan) => void; saving: boolean }) {
    const [draft, setDraft] = useState<Plan>(plan);
    const dirty = JSON.stringify(draft) !== JSON.stringify(plan);

    return (
        <div className="space-y-3">
            <div className="grid gap-2 sm:grid-cols-2 lg:grid-cols-3">
                {LIMIT_FIELDS.map((f) => (
                    <label key={f.key} className="block">
                        <span className="mb-1 block text-[0.78rem] text-ink-3">{f.label}</span>
                        <input
                            type="number"
                            value={draft.base_limits[f.key]}
                            onChange={(e) =>
                                setDraft({
                                    ...draft,
                                    base_limits: {
                                        ...draft.base_limits,
                                        [f.key]: Number(e.target.value),
                                    },
                                })
                            }
                            className="w-full rounded border border-rule bg-panel px-2 py-1.5 text-[0.85rem] text-ink"
                        />
                        <span className="mt-0.5 block text-[0.72rem] text-ink-3">−1 is unlimited</span>
                    </label>
                ))}
                <label className="block">
                    <span className="mb-1 block text-[0.78rem] text-ink-3">Support level</span>
                    <select
                        value={draft.support_level}
                        onChange={(e) => setDraft({ ...draft, support_level: e.target.value })}
                        className="w-full rounded border border-rule bg-panel px-2 py-1.5 text-[0.85rem] text-ink"
                    >
                        {SUPPORT_LEVELS.map((s) => (
                            <option key={s.value} value={s.value}>
                                {s.label}
                            </option>
                        ))}
                    </select>
                </label>
            </div>

            <label className="flex items-center gap-2 text-[0.85rem] text-ink-2">
                <input type="checkbox" checked={draft.active} onChange={(e) => setDraft({ ...draft, active: e.target.checked })} />
                Offered to customers
            </label>

            <p className="text-[0.78rem] text-ink-3">Changes apply to licences issued from now on. Existing licences snapshotted their plan and are unaffected.</p>

            <button type="button" disabled={!dirty || saving} onClick={() => onSave(draft)} className="rounded border border-accent/50 px-3 py-1.5 text-[0.85rem] text-accent disabled:opacity-40">
                {saving ? "Saving…" : "Save allowances"}
            </button>
        </div>
    );
}

export default function PlansPage() {
    const qc = useQueryClient();
    const plans = useQuery({ queryKey: ["plans"], queryFn: api.staff.plans });
    const licenses = useQuery({
        queryKey: ["staff-licenses"],
        queryFn: () => api.staff.licenses(),
    });
    const [draft, setDraft] = useState<Plan | null>(null);
    const [saving, setSaving] = useState<string | null>(null);

    const save = useMutation({
        mutationFn: (p: Plan) => api.staff.updatePlan(p.deployment, p.tier, p),
        onSuccess: () => {
            qc.invalidateQueries({ queryKey: ["plans"] });
            setDraft(null);
            setSaving(null);
        },
        onError: () => setSaving(null),
    });

    const original = plans.data?.find((p) => p.deployment === draft?.deployment && p.tier === draft?.tier);

    return (
        <div className="grid gap-6">
            <PageHeader
                title="Plans"
                subtitle="The authoritative tier table six plans, two deployments by three tiers, base allowances only. Every issued licence snapshots the plan it was cut from, so editing one never rewrites an existing licence."
            />

            {draft && original && (
                <ConfirmPlanChange
                    plan={original}
                    next={draft}
                    issuedCount={(licenses.data ?? []).filter((l) => l.tier === draft.tier && l.deployment === draft.deployment).length}
                    onConfirm={() => {
                        setSaving(`${draft.deployment}/${draft.tier}`);
                        save.mutate(draft);
                    }}
                    onCancel={() => setDraft(null)}
                />
            )}

            {(["cloud", "self_hosted"] as const).map((deployment: Deployment) => (
                <section key={deployment} className="space-y-3">
                    <h2 className="text-[0.95rem] font-medium text-ink">{deployment === "cloud" ? "Cloud" : "Self-Hosted"}</h2>
                    {(plans.data ?? [])
                        .filter((p) => p.deployment === deployment)
                        .map((p) => (
                            <article key={`${p.deployment}/${p.tier}`} className="rounded-lg border border-rule bg-panel p-4">
                                <header className="mb-3 flex items-baseline justify-between gap-3">
                                    <h3 className="text-[0.9rem] font-medium text-ink">{p.name}</h3>
                                    <span className="font-mono text-[0.75rem] text-ink-3">
                                        {p.deployment}/{p.tier}
                                    </span>
                                </header>
                                <AllowanceForm plan={p} saving={saving === `${p.deployment}/${p.tier}`} onSave={(next: Plan) => setDraft(next)} />
                            </article>
                        ))}
                </section>
            ))}
        </div>
    );
}
