"use client";

import { useRef } from "react";
import { clsx } from "clsx";

/*
 * The tab bar under the faceplate.
 *
 * Below md it is a select instead. Five tabs do not fit a phone, and the two
 * usual answers are both worse: wrapping to a second row changes the height of
 * the sticky header as the selection moves, and a horizontally scrolling strip
 * hides tabs off the right edge with nothing saying they are there. A select
 * shows every section and its count in one list, and it is the platform's own
 * picker, so it needs no scroll affordance of ours.
 *
 * Counts live on the labels because that is the only way an operator learns
 * there is something wrong on a tab they are not looking at. A count with a
 * tone is still labelled by its tab name, so tone is never the whole message —
 * and in the select, where tone cannot survive, the count still does.
 */

export type TabId = "overview" | "workloads" | "security" | "access" | "maintenance";

export interface TabSpec {
    id: TabId;
    label: string;
    count?: number;
    tone?: "neutral" | "warning" | "danger";
}

export function ServerTabs({ tabs, active, onSelect }: { tabs: TabSpec[]; active: TabId; onSelect: (id: TabId) => void }) {
    const refs = useRef<Record<string, HTMLButtonElement | null>>({});

    function onKeyDown(e: React.KeyboardEvent) {
        if (e.key !== "ArrowRight" && e.key !== "ArrowLeft") return;
        e.preventDefault();
        const i = tabs.findIndex((t) => t.id === active);
        const next = tabs[(i + (e.key === "ArrowRight" ? 1 : -1) + tabs.length) % tabs.length];
        onSelect(next.id);
        refs.current[next.id]?.focus();
    }

    const current = tabs.find((t) => t.id === active);

    return (
        <>
            {/* Phone: the whole set in one picker, sitting on the same row as the
                section it names so the header keeps its height. */}
            <div className="pb-3 md:hidden">
                <label htmlFor="server-tab-select" className="sr-only">
                    Server section
                </label>
                <div className="relative">
                    <select
                        id="server-tab-select"
                        value={active}
                        onChange={(e) => onSelect(e.target.value as TabId)}
                        className="w-full appearance-none rounded border border-border bg-surface-2 py-2 pl-3 pr-9 text-sm font-semibold text-text-primary focus:border-accent/50 focus:outline-none focus:ring-1 focus:ring-accent/30"
                    >
                        {tabs.map((tab) => (
                            <option key={tab.id} value={tab.id}>
                                {tab.label}
                                {tab.count !== undefined && tab.count > 0 ? ` (${tab.count})` : ""}
                            </option>
                        ))}
                    </select>
                    <svg className="pointer-events-none absolute right-3 top-1/2 h-4 w-4 -translate-y-1/2 text-text-secondary" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}>
                        <path strokeLinecap="round" strokeLinejoin="round" d="M6 9l6 6 6-6" />
                    </svg>
                </div>
                {current?.count !== undefined && current.count > 0 && current.tone && current.tone !== "neutral" && (
                    <p className={clsx("mt-1.5 text-xs", current.tone === "danger" ? "text-danger" : "text-warning")}>
                        {current.count} item{current.count !== 1 ? "s" : ""} in {current.label.toLowerCase()}
                    </p>
                )}
            </div>

            <div role="tablist" aria-label="Server sections" onKeyDown={onKeyDown} className="-mb-px hidden gap-1 md:flex">
            {tabs.map((tab) => {
                const isActive = tab.id === active;
                return (
                    <button
                        key={tab.id}
                        ref={(el) => {
                            refs.current[tab.id] = el;
                        }}
                        type="button"
                        role="tab"
                        id={`server-tab-${tab.id}`}
                        aria-selected={isActive}
                        aria-controls={`server-panel-${tab.id}`}
                        tabIndex={isActive ? 0 : -1}
                        onClick={() => onSelect(tab.id)}
                        className={clsx(
                            "flex shrink-0 items-center gap-2 whitespace-nowrap border-b-2 px-3 py-2.5 text-sm transition-colors",
                            isActive ? "border-accent font-semibold text-text-primary" : "border-transparent font-medium text-text-secondary hover:text-text-primary",
                        )}
                    >
                        {tab.label}
                        {tab.count !== undefined && tab.count > 0 && (
                            <span
                                className={clsx(
                                    "rounded-full border px-1.5 py-px font-mono text-[0.62rem] tabular-nums",
                                    tab.tone === "danger"
                                        ? "border-danger/40 bg-danger/10 text-danger"
                                        : tab.tone === "warning"
                                          ? "border-warning/40 bg-warning/10 text-warning"
                                          : "border-border bg-surface-2 text-text-secondary",
                                )}
                            >
                                {tab.count}
                            </span>
                        )}
                    </button>
                );
            })}
            </div>
        </>
    );
}
