"use client";
import { jsx, jsxs } from "react/jsx-runtime";
import * as React from "react";
import { Check, Search } from "lucide-react";
import {
  Popover,
  PopoverContent,
  PopoverTrigger
} from "@open-mercato/ui/primitives/popover";
import { Button } from "@open-mercato/ui/primitives/button";
import { Spinner } from "@open-mercato/ui/primitives/spinner";
import { useT } from "@open-mercato/shared/lib/i18n/context";
import { translateWithFallback } from "@open-mercato/shared/lib/i18n/translate";
import { ChipButton } from "./ChipButton.js";
import { FilterPopoverShell } from "./FilterPopoverShell.js";
const DEBOUNCE_MS = 250;
function EntityFilterPopover({
  label,
  values,
  onApply,
  initialOptions,
  loadOptions,
  labelById,
  anyLabel,
  title
}) {
  const t = useT();
  const [open, setOpen] = React.useState(false);
  const [draft, setDraft] = React.useState(values);
  const [query, setQuery] = React.useState("");
  const [options, setOptions] = React.useState(initialOptions ?? []);
  const [isLoading, setIsLoading] = React.useState(false);
  React.useEffect(() => {
    if (open) {
      setDraft(values);
      setQuery("");
      setOptions(initialOptions ?? []);
    }
  }, [open, values, initialOptions]);
  React.useEffect(() => {
    if (!open) return;
    const controller = new AbortController();
    const handle = window.setTimeout(async () => {
      setIsLoading(true);
      try {
        const items = await loadOptions(query, controller.signal);
        setOptions(items);
      } catch (err) {
        if (controller.signal.aborted) return;
      } finally {
        setIsLoading(false);
      }
    }, DEBOUNCE_MS);
    return () => {
      window.clearTimeout(handle);
      controller.abort();
    };
  }, [open, query, loadOptions]);
  const chipValue = React.useMemo(() => {
    if (values.length === 0) {
      return anyLabel ?? translateWithFallback(t, "customers.deals.kanban.filter.any", "Any");
    }
    if (values.length === 1) {
      const id = values[0];
      const fromLabels = labelById?.[id];
      if (fromLabels) return fromLabels;
      const fromOptions = options.find((option) => option.value === id)?.label;
      if (fromOptions) return fromOptions;
      return id.slice(0, 8);
    }
    return translateWithFallback(
      t,
      "customers.deals.kanban.filter.multipleSelected",
      "{count} selected",
      { count: values.length }
    );
  }, [values, anyLabel, labelById, options, t]);
  const toggleDraft = (id) => {
    setDraft((prev) => prev.includes(id) ? prev.filter((value) => value !== id) : [...prev, id]);
  };
  const handleApply = () => {
    onApply(draft);
    setOpen(false);
  };
  const handleClear = () => {
    setDraft([]);
  };
  const handleKeyDown = (event) => {
    if ((event.metaKey || event.ctrlKey) && event.key === "Enter") {
      event.preventDefault();
      handleApply();
    }
  };
  const headerTitle = title ?? translateWithFallback(
    t,
    "customers.deals.kanban.filter.title",
    "Filter \xB7 {label}",
    { label }
  );
  const footerLeft = /* @__PURE__ */ jsxs("div", { className: "flex items-center gap-3", children: [
    /* @__PURE__ */ jsx("span", { children: draft.length === 0 ? translateWithFallback(t, "customers.deals.kanban.filter.noneSelected", "None selected") : translateWithFallback(
      t,
      "customers.deals.kanban.filter.countSelected",
      "{count} selected",
      { count: draft.length }
    ) }),
    draft.length > 0 ? /* @__PURE__ */ jsx(
      Button,
      {
        type: "button",
        variant: "link",
        size: "2xs",
        onClick: handleClear,
        className: "h-auto px-0 text-xs font-medium leading-normal text-muted-foreground hover:text-foreground",
        children: translateWithFallback(t, "customers.deals.kanban.filter.clear", "Clear")
      }
    ) : null
  ] });
  return /* @__PURE__ */ jsxs(Popover, { open, onOpenChange: setOpen, children: [
    /* @__PURE__ */ jsx(PopoverTrigger, { asChild: true, children: /* @__PURE__ */ jsx(ChipButton, { label, value: chipValue, active: values.length > 0 }) }),
    /* @__PURE__ */ jsx(
      PopoverContent,
      {
        className: "w-96 rounded-2xl border-border bg-transparent p-0 shadow-xl",
        align: "start",
        onKeyDown: handleKeyDown,
        children: /* @__PURE__ */ jsxs(
          FilterPopoverShell,
          {
            title: headerTitle,
            onClose: () => setOpen(false),
            onCancel: () => setOpen(false),
            onApply: handleApply,
            footerLeft,
            bodyClassName: "flex flex-col bg-card",
            children: [
              /* @__PURE__ */ jsxs("div", { className: "flex items-center gap-2 border-b border-border px-4 py-2.5", children: [
                /* @__PURE__ */ jsx(Search, { className: "size-4 shrink-0 text-muted-foreground", "aria-hidden": "true" }),
                /* @__PURE__ */ jsx(
                  "input",
                  {
                    type: "text",
                    value: query,
                    onChange: (e) => setQuery(e.target.value),
                    placeholder: translateWithFallback(
                      t,
                      "customers.deals.kanban.filter.searchPlaceholder",
                      "Search\u2026"
                    ),
                    className: "h-7 w-full bg-transparent text-sm leading-normal text-foreground outline-none placeholder:text-muted-foreground",
                    autoFocus: true
                  }
                ),
                isLoading ? /* @__PURE__ */ jsx(Spinner, { className: "size-3" }) : null
              ] }),
              /* @__PURE__ */ jsx("div", { className: "max-h-64 overflow-y-auto", children: options.length === 0 && !isLoading ? /* @__PURE__ */ jsx("div", { className: "px-4 py-6 text-center text-xs text-muted-foreground", children: translateWithFallback(t, "customers.deals.kanban.filter.noResults", "No matches") }) : /* @__PURE__ */ jsx("ul", { className: "py-1", children: options.map((option) => {
                const checked = draft.includes(option.value);
                return /* @__PURE__ */ jsx("li", { children: /* @__PURE__ */ jsxs(
                  Button,
                  {
                    type: "button",
                    variant: "ghost",
                    role: "checkbox",
                    "aria-checked": checked,
                    onClick: () => toggleDraft(option.value),
                    className: `h-auto w-full justify-start gap-3 rounded-none px-4 py-2.5 text-left font-normal ${checked ? "bg-muted/60" : "bg-card"}`,
                    children: [
                      /* @__PURE__ */ jsx(
                        "span",
                        {
                          className: `flex size-4 shrink-0 items-center justify-center rounded-sm border ${checked ? "border-accent-indigo bg-accent-indigo text-accent-indigo-foreground" : "border-input bg-card"}`,
                          "aria-hidden": "true",
                          children: checked ? /* @__PURE__ */ jsx(Check, { className: "size-3" }) : null
                        }
                      ),
                      /* @__PURE__ */ jsx(
                        "span",
                        {
                          className: `truncate text-sm leading-normal text-foreground ${checked ? "font-semibold" : "font-normal"}`,
                          children: option.label
                        }
                      )
                    ]
                  }
                ) }, option.value);
              }) }) })
            ]
          }
        )
      }
    )
  ] });
}
var EntityFilterPopover_default = EntityFilterPopover;
export {
  EntityFilterPopover,
  EntityFilterPopover_default as default
};
//# sourceMappingURL=EntityFilterPopover.js.map
