"use client";

import { useMutation, useQueryClient } from "@tanstack/react-query";
import { useState } from "react";
import { ApiError, api, type Tier } from "@/lib/api";
import { Button } from "@/components/Button";
import { Field } from "@/components/Field";

export function IssuePanel({ instanceId }: { instanceId: string }) {
    const qc = useQueryClient();
    const [tier, setTier] = useState<Tier>("professional");
    const [term, setTerm] = useState("annual");
    const [newId, setNewId] = useState("");
    const [error, setError] = useState<string | undefined>();

    const invalidate = () => qc.invalidateQueries({ queryKey: ["staff-instance", instanceId] });

    const issue = useMutation({
        mutationFn: () => api.staff.issue(instanceId, { tier, term, reason: "manual" }),
        onSuccess: invalidate,
        onError: (e) => setError(e instanceof ApiError ? e.message : "Issue failed."),
    });

    const relink = useMutation({
        mutationFn: () => api.staff.relink(instanceId, newId.trim()),
        onSuccess: invalidate,
        onError: (e) => setError(e instanceof ApiError ? e.message : "Relink failed."),
    });

    return (
        <section className="grid gap-4 border-t border-rule-soft pt-5">
            <div className="flex flex-wrap items-end gap-3">
                <label className="grid gap-1.5">
                    <span className="font-mono text-[0.72rem] uppercase tracking-[0.1em] text-ink-3">Tier</span>
                    <select value={tier} onChange={(e) => setTier(e.target.value as Tier)} className="rounded border border-rule bg-panel-2 px-2.5 py-2">
                        <option value="free">Free</option>
                        <option value="professional">Professional</option>
                        <option value="enterprise">Enterprise</option>
                    </select>
                </label>
                <label className="grid gap-1.5">
                    <span className="font-mono text-[0.72rem] uppercase tracking-[0.1em] text-ink-3">Term</span>
                    <select value={term} onChange={(e) => setTerm(e.target.value)} className="rounded border border-rule bg-panel-2 px-2.5 py-2">
                        <option value="annual">Annual</option>
                        <option value="monthly">Monthly</option>
                    </select>
                </label>
                <Button type="button" onClick={() => issue.mutate()} disabled={issue.isPending}>
                    {issue.isPending ? "Issuing…" : "Issue licence"}
                </Button>
            </div>

            <div className="flex flex-wrap items-end gap-3">
                <Field label="Relink to instance ID" value={newId} onChange={(e) => setNewId(e.target.value)} hint="Staff relinks are not capped the customer cap exists to put you in the loop." />
                <Button type="button" variant="line" onClick={() => relink.mutate()} disabled={!newId.trim()}>
                    Relink
                </Button>
            </div>

            {error && <p className="text-[0.82rem] text-expired">{error}</p>}
        </section>
    );
}
