"use client";
import { Fragment, jsx, jsxs } from "react/jsx-runtime";
import * as React from "react";
import { Box, Check, ChevronDown, Plus } from "lucide-react";
import { cn } from "@open-mercato/shared/lib/utils";
import { useT } from "@open-mercato/shared/lib/i18n/context";
import { Button } from "@open-mercato/ui/primitives/button";
import { IconButton } from "@open-mercato/ui/primitives/icon-button";
import { Input } from "@open-mercato/ui/primitives/input";
import { fetchResourceTypes, searchResourceOptions } from "./lookups.js";
import { CONTROL_BORDER, DROPDOWN_PANEL_CLASS, useDropdownDismiss } from "./inputs.js";
const TYPE_SEARCH_THRESHOLD = 8;
function ResourcesField({
  placeholder,
  ariaLabel,
  value,
  onChange
}) {
  const t = useT();
  const [query, setQuery] = React.useState("");
  const [open, setOpen] = React.useState(false);
  const [options, setOptions] = React.useState([]);
  const [total, setTotal] = React.useState(0);
  const [loading, setLoading] = React.useState(false);
  const [types, setTypes] = React.useState([]);
  const [typeFilter, setTypeFilter] = React.useState(null);
  const [typeMenuOpen, setTypeMenuOpen] = React.useState(false);
  const [typeQuery, setTypeQuery] = React.useState("");
  const close = React.useCallback(() => {
    setOpen(false);
    setTypeMenuOpen(false);
  }, []);
  const rootRef = useDropdownDismiss(open, close);
  React.useEffect(() => {
    if (!open || types.length > 0) return;
    const controller = new AbortController();
    let cancelled = false;
    fetchResourceTypes(controller.signal).then((found) => {
      if (!cancelled) setTypes(found);
    });
    return () => {
      cancelled = true;
      controller.abort();
    };
  }, [open, types.length]);
  React.useEffect(() => {
    if (!open) return;
    const controller = new AbortController();
    let cancelled = false;
    const timer = window.setTimeout(async () => {
      setLoading(true);
      try {
        const result = await searchResourceOptions({ query: query.trim(), resourceTypeId: typeFilter }, controller.signal);
        if (cancelled) return;
        setOptions(result.items);
        setTotal(result.total);
      } catch {
        if (!cancelled) {
          setOptions([]);
          setTotal(0);
        }
      } finally {
        if (!cancelled) setLoading(false);
      }
    }, 250);
    return () => {
      cancelled = true;
      controller.abort();
      window.clearTimeout(timer);
    };
  }, [open, query, typeFilter]);
  const selectedIds = new Set(value.map((resource) => resource.id));
  const visibleOptions = options.filter((option) => !selectedIds.has(option.id));
  const hiddenCount = Math.max(0, total - options.length);
  const activeType = typeFilter ? types.find((type) => type.id === typeFilter) ?? null : null;
  const filteredTypes = typeQuery.trim().length ? types.filter((type) => type.name.toLowerCase().includes(typeQuery.trim().toLowerCase())) : types;
  const selectType = (id) => {
    setTypeFilter(id);
    setTypeMenuOpen(false);
    setTypeQuery("");
  };
  return /* @__PURE__ */ jsxs(
    "div",
    {
      ref: rootRef,
      className: "relative w-full",
      onBlur: (event) => {
        if (!event.currentTarget.contains(event.relatedTarget)) close();
      },
      children: [
        /* @__PURE__ */ jsxs(
          "div",
          {
            className: cn(
              "flex min-h-14 w-full flex-wrap content-center items-center gap-2 rounded-md bg-background px-2.5 py-2",
              CONTROL_BORDER
            ),
            children: [
              value.map((resource) => /* @__PURE__ */ jsxs("span", { className: "inline-flex shrink-0 items-center gap-1.5 rounded-full bg-muted py-1 pl-2 pr-2", children: [
                /* @__PURE__ */ jsx(Box, { "aria-hidden": true, className: "size-3.5 text-muted-foreground" }),
                /* @__PURE__ */ jsx("span", { className: "max-w-40 truncate text-xs font-medium text-foreground", children: resource.label }),
                /* @__PURE__ */ jsx(
                  IconButton,
                  {
                    variant: "ghost",
                    size: "xs",
                    onClick: (event) => {
                      event.stopPropagation();
                      onChange(value.filter((entry) => entry.id !== resource.id));
                    },
                    "aria-label": t("customers.calendar.editor.removeResource", "Remove {name}", { name: resource.label }),
                    className: "size-5 shrink-0",
                    children: /* @__PURE__ */ jsx(Plus, { "aria-hidden": true, className: "size-3.5 rotate-45 opacity-50" })
                  }
                )
              ] }, resource.id)),
              /* @__PURE__ */ jsx(
                Input,
                {
                  type: "text",
                  value: query,
                  onChange: (event) => setQuery(event.target.value),
                  onFocus: () => setOpen(true),
                  placeholder: value.length > 0 ? "" : placeholder,
                  "aria-label": ariaLabel,
                  role: "combobox",
                  "aria-expanded": open,
                  className: "min-w-36 flex-1 border-0 bg-transparent px-0 shadow-none hover:bg-transparent focus-within:border-transparent focus-within:shadow-none",
                  inputClassName: "text-sm text-foreground placeholder:text-muted-foreground"
                }
              )
            ]
          }
        ),
        open ? /* @__PURE__ */ jsxs("div", { className: cn(DROPDOWN_PANEL_CLASS, "flex max-h-none flex-col overflow-visible p-0"), children: [
          types.length > 0 ? /* @__PURE__ */ jsx("div", { className: "border-b border-border p-1.5", children: /* @__PURE__ */ jsxs(
            Button,
            {
              type: "button",
              variant: "outline",
              "aria-haspopup": "listbox",
              "aria-expanded": typeMenuOpen,
              onClick: () => setTypeMenuOpen((previous) => !previous),
              className: cn("h-8 w-full justify-between bg-background px-2 text-sm font-normal shadow-none", CONTROL_BORDER),
              children: [
                /* @__PURE__ */ jsx("span", { className: "truncate", children: activeType ? `${activeType.name} (${activeType.count})` : t("customers.calendar.editor.resourceTypes.all", "All types") }),
                /* @__PURE__ */ jsx(ChevronDown, { "aria-hidden": true, className: "size-4 shrink-0 opacity-60" })
              ]
            }
          ) }) : null,
          typeMenuOpen ? /* @__PURE__ */ jsxs("div", { role: "listbox", "aria-label": t("customers.calendar.editor.resourceTypes.filterLabel", "Resource type"), className: "flex flex-col", children: [
            types.length > TYPE_SEARCH_THRESHOLD ? /* @__PURE__ */ jsx("div", { className: "border-b border-border p-1.5", children: /* @__PURE__ */ jsx(
              Input,
              {
                type: "text",
                value: typeQuery,
                onChange: (event) => setTypeQuery(event.target.value),
                placeholder: t("customers.calendar.editor.resourceTypes.searchPlaceholder", "Search types\u2026"),
                "aria-label": t("customers.calendar.editor.resourceTypes.searchPlaceholder", "Search types\u2026"),
                autoFocus: true,
                className: "h-8"
              }
            ) }) : null,
            /* @__PURE__ */ jsxs("div", { className: "max-h-56 overflow-y-auto p-1", children: [
              /* @__PURE__ */ jsx(TypeRow, { label: t("customers.calendar.editor.resourceTypes.all", "All types"), active: typeFilter === null, onSelect: () => selectType(null) }),
              filteredTypes.map((type) => /* @__PURE__ */ jsx(TypeRow, { label: type.name, count: type.count, active: typeFilter === type.id, onSelect: () => selectType(type.id) }, type.id)),
              filteredTypes.length === 0 ? /* @__PURE__ */ jsx("p", { className: "px-2 py-3 text-center text-xs text-muted-foreground", children: t("customers.calendar.editor.noResults", "No results") }) : null
            ] })
          ] }) : /* @__PURE__ */ jsxs(Fragment, { children: [
            /* @__PURE__ */ jsxs("div", { role: "listbox", "aria-label": ariaLabel, className: "max-h-56 overflow-y-auto p-1", children: [
              loading ? /* @__PURE__ */ jsx("p", { className: "px-2 py-3 text-center text-xs text-muted-foreground", children: t("customers.calendar.editor.searching", "Searching\u2026") }) : null,
              !loading && visibleOptions.length === 0 ? /* @__PURE__ */ jsx("p", { className: "px-2 py-3 text-center text-xs text-muted-foreground", children: t("customers.calendar.editor.noResults", "No results") }) : null,
              !loading ? visibleOptions.map((option) => /* @__PURE__ */ jsxs(
                Button,
                {
                  type: "button",
                  variant: "ghost",
                  role: "option",
                  "aria-selected": false,
                  title: option.label,
                  onClick: () => {
                    onChange([...value, { id: option.id, label: option.label }]);
                    setQuery("");
                  },
                  className: "h-auto w-full justify-start gap-2 whitespace-normal px-2 py-1.5 text-left text-sm font-normal text-foreground",
                  children: [
                    /* @__PURE__ */ jsx(Box, { "aria-hidden": true, className: "size-4 text-muted-foreground" }),
                    /* @__PURE__ */ jsx("span", { className: "min-w-0 flex-1 truncate", children: option.label })
                  ]
                },
                option.id
              )) : null
            ] }),
            !loading && hiddenCount > 0 ? /* @__PURE__ */ jsx("p", { className: "border-t border-border px-2 py-1.5 text-center text-xs text-muted-foreground", children: t("customers.calendar.editor.resourceTypes.moreHint", "Showing {shown} of {total} \u2014 keep typing to narrow", {
              shown: options.length,
              total
            }) }) : null
          ] })
        ] }) : null
      ]
    }
  );
}
function TypeRow({ label, count, active, onSelect }) {
  return /* @__PURE__ */ jsxs(
    Button,
    {
      type: "button",
      variant: "ghost",
      role: "option",
      "aria-selected": active,
      onClick: onSelect,
      className: cn("h-auto w-full justify-start gap-2 px-2 py-1.5 text-left text-sm font-normal", active ? "bg-muted text-foreground" : "text-foreground"),
      children: [
        /* @__PURE__ */ jsx(Check, { "aria-hidden": true, className: cn("size-4 shrink-0", active ? "opacity-100" : "opacity-0") }),
        /* @__PURE__ */ jsx("span", { className: "min-w-0 flex-1 truncate", children: label }),
        typeof count === "number" ? /* @__PURE__ */ jsx("span", { className: "shrink-0 tabular-nums text-xs text-muted-foreground", children: count }) : null
      ]
    }
  );
}
export {
  ResourcesField
};
//# sourceMappingURL=ResourcesField.js.map
