"use client";
import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
import { useCallback, useId, useMemo } from "react";
import { cn } from "@stigmer/theme";
import { useEnvironmentList } from "./useEnvironmentList";
/**
 * Multi-select component for binding Environment resources to an instance.
 *
 * Displays available environments as a dropdown and shows selected environments
 * as an ordered list with position numbers indicating merge priority.
 * Later entries override earlier ones when keys conflict.
 *
 * Uses `useEnvironmentList(org)` for data. Arrow buttons provide accessible
 * reordering without requiring drag-and-drop libraries.
 *
 * @example
 * ```tsx
 * <EnvironmentPicker
 *   org="acme"
 *   value={environmentRefs}
 *   onChange={setEnvironmentRefs}
 * />
 * ```
 */
export function EnvironmentPicker({ org, value, onChange, disabled = false, className, }) {
    const { environments, isLoading } = useEnvironmentList(org);
    const selectId = useId();
    const selectedSlugs = useMemo(() => new Set(value.map((ref) => ref.slug)), [value]);
    const availableEnvironments = useMemo(() => environments.filter((env) => !selectedSlugs.has(env.metadata?.slug ?? "")), [environments, selectedSlugs]);
    const handleAdd = useCallback((slug) => {
        const env = environments.find((e) => e.metadata?.slug === slug);
        if (!env)
            return;
        const ref = { org, slug: env.metadata.slug };
        onChange([...value, ref]);
    }, [environments, onChange, org, value]);
    const handleRemove = useCallback((index) => {
        const next = [...value];
        next.splice(index, 1);
        onChange(next);
    }, [onChange, value]);
    const handleMoveUp = useCallback((index) => {
        if (index === 0)
            return;
        const next = [...value];
        [next[index - 1], next[index]] = [next[index], next[index - 1]];
        onChange(next);
    }, [onChange, value]);
    const handleMoveDown = useCallback((index) => {
        if (index >= value.length - 1)
            return;
        const next = [...value];
        [next[index], next[index + 1]] = [next[index + 1], next[index]];
        onChange(next);
    }, [onChange, value]);
    const resolveEnvName = useCallback((ref) => {
        const env = environments.find((e) => e.metadata?.slug === ref.slug);
        return env?.metadata?.name ?? ref.slug;
    }, [environments]);
    const resolveEnvDescription = useCallback((ref) => {
        const env = environments.find((e) => e.metadata?.slug === ref.slug);
        return env?.spec?.description ?? "";
    }, [environments]);
    return (_jsxs("div", { className: cn("space-y-3", className), role: "group", "aria-label": "Environment bindings", children: [value.length > 0 && (_jsx(SelectedList, { value: value, disabled: disabled, resolveEnvName: resolveEnvName, resolveEnvDescription: resolveEnvDescription, onRemove: handleRemove, onMoveUp: handleMoveUp, onMoveDown: handleMoveDown, total: value.length })), value.length > 1 && (_jsx("p", { className: "text-[0.65rem] text-muted-foreground", children: "Environments are merged in order. Later entries override earlier ones when keys conflict." })), _jsxs("div", { children: [_jsx("label", { htmlFor: selectId, className: "sr-only", children: "Add environment" }), _jsxs("select", { id: selectId, disabled: disabled || availableEnvironments.length === 0, value: "", onChange: (e) => {
                            if (e.target.value)
                                handleAdd(e.target.value);
                        }, className: cn("w-full rounded-md border border-border bg-background px-3 py-1.5 text-sm", "text-foreground placeholder:text-muted-foreground", "focus:outline-none focus:ring-2 focus:ring-ring", "disabled:cursor-not-allowed disabled:opacity-50"), children: [_jsx("option", { value: "", children: isLoading
                                    ? "Loading environments..."
                                    : availableEnvironments.length === 0
                                        ? value.length === environments.length && environments.length > 0
                                            ? "All environments selected"
                                            : "No environments available"
                                        : "+ Add environment" }), availableEnvironments.map((env) => (_jsx("option", { value: env.metadata?.slug, children: env.metadata?.name ?? env.metadata?.slug }, env.metadata?.slug)))] })] })] }));
}
function SelectedList({ value, disabled, resolveEnvName, resolveEnvDescription, onRemove, onMoveUp, onMoveDown, total, }) {
    return (_jsx("ol", { className: "space-y-1.5", "aria-label": "Selected environments (merge order)", children: value.map((ref, index) => (_jsxs("li", { className: cn("flex items-center gap-2 rounded-md border border-border px-3 py-2", "bg-muted/30"), children: [_jsxs("span", { className: "shrink-0 w-5 text-xs font-medium text-muted-foreground text-right", children: [index + 1, "."] }), _jsxs("div", { className: "flex-1 min-w-0", children: [_jsx("span", { className: "text-sm font-medium text-foreground truncate block", children: resolveEnvName(ref) }), resolveEnvDescription(ref) && (_jsx("span", { className: "text-[0.65rem] text-muted-foreground truncate block", children: resolveEnvDescription(ref) }))] }), !disabled && (_jsxs("div", { className: "flex items-center gap-0.5 shrink-0", children: [_jsx(ReorderButton, { direction: "up", disabled: index === 0, onClick: () => onMoveUp(index), label: `Move ${resolveEnvName(ref)} up` }), _jsx(ReorderButton, { direction: "down", disabled: index === total - 1, onClick: () => onMoveDown(index), label: `Move ${resolveEnvName(ref)} down` }), _jsx("button", { type: "button", onClick: () => onRemove(index), "aria-label": `Remove ${resolveEnvName(ref)}`, className: cn("rounded p-1 text-muted-foreground", "hover:text-destructive hover:bg-destructive/10", "focus:outline-none focus:ring-1 focus:ring-ring"), children: _jsx(RemoveIcon, {}) })] }))] }, `${ref.org}-${ref.slug}-${index}`))) }));
}
function ReorderButton({ direction, disabled, onClick, label, }) {
    return (_jsx("button", { type: "button", disabled: disabled, onClick: onClick, "aria-label": label, className: cn("rounded p-1 text-muted-foreground", "hover:text-foreground hover:bg-accent-hover", "focus:outline-none focus:ring-1 focus:ring-ring", "disabled:opacity-30 disabled:cursor-not-allowed disabled:hover:bg-transparent"), children: direction === "up" ? _jsx(ArrowUpIcon, {}) : _jsx(ArrowDownIcon, {}) }));
}
function ArrowUpIcon() {
    return (_jsx("svg", { width: "12", height: "12", viewBox: "0 0 12 12", fill: "none", "aria-hidden": "true", children: _jsx("path", { d: "M6 2.5v7M6 2.5L3 5.5M6 2.5l3 3", stroke: "currentColor", strokeWidth: "1.5", strokeLinecap: "round", strokeLinejoin: "round" }) }));
}
function ArrowDownIcon() {
    return (_jsx("svg", { width: "12", height: "12", viewBox: "0 0 12 12", fill: "none", "aria-hidden": "true", children: _jsx("path", { d: "M6 9.5v-7M6 9.5L3 6.5M6 9.5l3-3", stroke: "currentColor", strokeWidth: "1.5", strokeLinecap: "round", strokeLinejoin: "round" }) }));
}
function RemoveIcon() {
    return (_jsx("svg", { width: "12", height: "12", viewBox: "0 0 12 12", fill: "none", "aria-hidden": "true", children: _jsx("path", { d: "M3 3l6 6M9 3l-6 6", stroke: "currentColor", strokeWidth: "1.5", strokeLinecap: "round" }) }));
}
//# sourceMappingURL=EnvironmentPicker.js.map