"use client";
import { jsx, jsxs } from "react/jsx-runtime";
import * as React from "react";
import { Loader2, Search, X } from "lucide-react";
import { Button } from "../../primitives/button.js";
import { cn } from "@open-mercato/shared/lib/utils";
function LookupSelect({
  value,
  onChange,
  fetchItems,
  fetchOptions,
  options,
  minQuery = 2,
  actionSlot,
  onReady,
  placeholder,
  searchPlaceholder = placeholder ?? "Search\u2026",
  clearLabel = "Clear selection",
  emptyLabel = "No results",
  loadingLabel = "Searching\u2026",
  selectLabel = "Select",
  selectedLabel = "Selected",
  minQueryHintLabel,
  startTypingLabel = "Start typing to search.",
  selectedHintLabel,
  disabled = false,
  loading: loadingProp = false,
  defaultOpen = false
}) {
  const [query, setQuery] = React.useState("");
  const [items, setItems] = React.useState(options ?? []);
  const [loading, setLoading] = React.useState(false);
  const [hasTyped, setHasTyped] = React.useState(defaultOpen);
  const [error, setError] = React.useState(null);
  const [fetchKey, setFetchKey] = React.useState(0);
  const fetchItemsRef = React.useRef(fetchItems ?? fetchOptions);
  const setQueryRef = React.useRef(setQuery);
  const optionsWasArrayRef = React.useRef(Array.isArray(options));
  React.useEffect(() => {
    fetchItemsRef.current = fetchItems ?? fetchOptions;
  }, [fetchItems, fetchOptions]);
  React.useEffect(() => {
    if (Array.isArray(options)) {
      optionsWasArrayRef.current = true;
      setItems(options);
    } else if (optionsWasArrayRef.current) {
      optionsWasArrayRef.current = false;
      setFetchKey((k) => k + 1);
    }
  }, [options]);
  React.useEffect(() => {
    setQueryRef.current = setQuery;
    if (onReady) onReady({ setQuery });
  }, [onReady, setQuery]);
  const shouldSearch = defaultOpen || query.trim().length >= minQuery || Boolean(value && (options?.length ?? 0) > 0);
  React.useEffect(() => {
    if (disabled) {
      setItems(options ?? []);
      setLoading(false);
      return;
    }
    let cancelled = false;
    let timer = null;
    if (!shouldSearch) {
      setItems(options ?? []);
      setLoading(false);
      setError(null);
      return () => {
        cancelled = true;
      };
    }
    setLoading(true);
    setError(null);
    timer = setTimeout(() => {
      const requestId = Date.now();
      const fetcher = fetchItemsRef.current;
      const loader = fetcher ?? (() => Promise.resolve(options ?? []));
      loader(query.trim()).then((result) => {
        if (cancelled) return;
        setItems(result);
      }).catch((err) => {
        if (cancelled) return;
        console.error("LookupSelect.fetchItems", err);
        setError("error");
      }).finally(() => {
        if (!cancelled) setLoading(false);
      });
      return requestId;
    }, 220);
    return () => {
      cancelled = true;
      if (timer) clearTimeout(timer);
    };
  }, [query, shouldSearch, fetchKey]);
  return /* @__PURE__ */ jsxs("div", { className: "space-y-3", children: [
    /* @__PURE__ */ jsxs("div", { className: "flex flex-col gap-2 sm:flex-row sm:items-center sm:gap-3", children: [
      /* @__PURE__ */ jsxs("div", { className: "relative flex-1", children: [
        /* @__PURE__ */ jsx(Search, { className: "pointer-events-none absolute left-2 top-2.5 h-4 w-4 text-muted-foreground" }),
        /* @__PURE__ */ jsx(
          "input",
          {
            className: "w-full rounded border pl-8 pr-2 py-2 text-sm",
            value: query,
            onChange: (event) => {
              setQuery(event.target.value);
              setHasTyped(true);
            },
            placeholder: searchPlaceholder,
            disabled
          }
        )
      ] }),
      actionSlot ? /* @__PURE__ */ jsx("div", { className: "sm:self-start", children: actionSlot }) : null
    ] }),
    shouldSearch ? /* @__PURE__ */ jsxs("div", { className: "space-y-2", children: [
      loading || loadingProp ? /* @__PURE__ */ jsxs("div", { className: "flex items-center gap-2 text-sm text-muted-foreground", children: [
        /* @__PURE__ */ jsx(Loader2, { className: "h-4 w-4 animate-spin" }),
        loadingLabel
      ] }) : null,
      !loading && !loadingProp && !items.length ? /* @__PURE__ */ jsx("p", { className: "text-xs text-muted-foreground", children: emptyLabel }) : null,
      /* @__PURE__ */ jsx("div", { className: "space-y-2 max-h-80 overflow-y-auto", children: items.map((item) => {
        const isSelected = value === item.id;
        return /* @__PURE__ */ jsxs(
          "div",
          {
            className: cn(
              "flex gap-3 rounded border bg-card p-3 transition-colors cursor-pointer focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50 focus-visible:ring-offset-2 focus-visible:ring-offset-background",
              isSelected ? "border-primary/70 bg-primary/5" : "hover:border-primary/50"
            ),
            role: "button",
            tabIndex: item.disabled ? -1 : 0,
            onClick: () => {
              if (item.disabled && !isSelected) return;
              onChange(item.id);
            },
            onKeyDown: (event) => {
              if (event.key === "Enter" || event.key === " ") {
                event.preventDefault();
                if (item.disabled && !isSelected) return;
                onChange(item.id);
              }
            },
            "aria-pressed": isSelected,
            children: [
              /* @__PURE__ */ jsx("div", { className: "flex h-10 w-10 sm:h-12 sm:w-12 shrink-0 items-center justify-center overflow-hidden rounded border bg-muted", children: item.icon ?? /* @__PURE__ */ jsx("span", { className: "text-muted-foreground", children: "\u2022" }) }),
              /* @__PURE__ */ jsxs("div", { className: "flex min-w-0 flex-1 flex-col gap-1", children: [
                /* @__PURE__ */ jsxs("div", { className: "flex items-start justify-between gap-2", children: [
                  /* @__PURE__ */ jsxs("div", { className: "min-w-0", children: [
                    /* @__PURE__ */ jsx("div", { className: "truncate text-sm font-medium", children: item.title }),
                    item.subtitle ? /* @__PURE__ */ jsx("div", { className: "text-xs text-muted-foreground truncate", children: item.subtitle }) : null,
                    item.description ? /* @__PURE__ */ jsx("div", { className: "text-xs text-muted-foreground truncate", children: item.description }) : null
                  ] }),
                  item.rightLabel ? /* @__PURE__ */ jsx("div", { className: "shrink-0 text-xs font-medium text-muted-foreground", children: item.rightLabel }) : null
                ] }),
                /* @__PURE__ */ jsx("div", { className: "flex justify-end", children: /* @__PURE__ */ jsx(
                  Button,
                  {
                    type: "button",
                    variant: isSelected ? "secondary" : "outline",
                    size: "sm",
                    className: "shrink-0",
                    onClick: (event) => {
                      event.stopPropagation();
                      if (item.disabled && !isSelected) return;
                      onChange(item.id);
                    },
                    disabled: item.disabled && !isSelected,
                    children: isSelected ? selectedLabel : selectLabel
                  }
                ) })
              ] })
            ]
          },
          item.id
        );
      }) }),
      value ? /* @__PURE__ */ jsxs(
        Button,
        {
          type: "button",
          variant: "ghost",
          size: "sm",
          className: "w-fit gap-1 text-sm font-normal",
          onClick: () => onChange(null),
          children: [
            /* @__PURE__ */ jsx(X, { className: "h-4 w-4" }),
            clearLabel
          ]
        }
      ) : null
    ] }) : hasTyped ? /* @__PURE__ */ jsx("p", { className: "text-xs text-muted-foreground", children: minQueryHintLabel ?? `Type at least ${minQuery} characters or paste an id to search.` }) : /* @__PURE__ */ jsx("p", { className: "text-xs text-muted-foreground", children: startTypingLabel }),
    error ? /* @__PURE__ */ jsx("p", { className: "text-xs text-destructive", children: emptyLabel }) : null
  ] });
}
export {
  LookupSelect
};
//# sourceMappingURL=LookupSelect.js.map
