"use client";

import { useState } from "react";
import { Button } from "./Button";
import { Field } from "./Field";

const UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;

export function RelinkPanel({
    used,
    max,
    onRelink,
    error,
}: {
    instanceId: string;
    used: number;
    max: number;
    onRelink: (newId: string) => void;
    error?: string;
}) {
    const [open, setOpen] = useState(false);
    const [value, setValue] = useState("");
    const remaining = Math.max(0, max - used);
    const exhausted = remaining === 0;

    return (
        <section className="grid gap-3 border-t border-rule-soft pt-5">
            <h2 className="text-xl">Moved to a new server?</h2>
            <p className="text-[0.82rem] text-ink-2">
                Relinking issues a replacement licence for the new install, covering the rest of
                your current term.
            </p>
            {open && !exhausted && (
                <Field
                    label="New instance ID"
                    value={value}
                    onChange={(e) => setValue(e.target.value)}
                    error={error}
                    hint="From Settings → Licence on the new install."
                />
            )}
            <div className="flex flex-wrap items-center gap-3">
                <Button
                    type="button"
                    variant="line"
                    disabled={exhausted || (open && !UUID_RE.test(value.trim()))}
                    onClick={() => (open ? onRelink(value.trim()) : setOpen(true))}
                >
                    Relink to a new install
                </Button>
                <span className="text-[0.82rem] text-ink-3">
                    {exhausted
                        ? "You have used every relink for this term — contact support and we will sort it out."
                        : `${remaining} of ${max} relinks left this term`}
                </span>
            </div>
        </section>
    );
}
