"use client";
import { Fragment, jsx, jsxs } from "react/jsx-runtime";
import * as React from "react";
import { Building2, ChevronDown, User, X } 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 { composeAccessibleName } from "../../../lib/calendar/labels.js";
import {
  fetchDealsForEntity,
  searchRelatedEntities
} from "./lookups.js";
import { CONTROL_BORDER, DROPDOWN_PANEL_CLASS, PersonChip, UppercaseBadge, useDropdownDismiss } from "./inputs.js";
const OPTION_ROW_CLASS = "h-auto w-full justify-start gap-2 whitespace-normal px-2 py-1.5 text-left text-sm font-normal text-foreground";
function RelatedToField({
  label,
  value,
  deal,
  onChange,
  onDealChange,
  error
}) {
  const t = useT();
  const [open, setOpen] = React.useState(false);
  const closeDropdown = React.useCallback(() => setOpen(false), []);
  const rootRef = useDropdownDismiss(open, closeDropdown);
  const [query, setQuery] = React.useState("");
  const [options, setOptions] = React.useState([]);
  const [deals, setDeals] = React.useState([]);
  const [loading, setLoading] = React.useState(false);
  React.useEffect(() => {
    if (!open) return;
    const controller = new AbortController();
    let cancelled = false;
    const timer = window.setTimeout(async () => {
      setLoading(true);
      try {
        const trimmed = query.trim();
        const [people, companies] = await Promise.all([
          searchRelatedEntities("person", trimmed, controller.signal),
          searchRelatedEntities("company", trimmed, controller.signal)
        ]);
        if (cancelled) return;
        setOptions([...people, ...companies]);
      } catch {
        if (!cancelled) setOptions([]);
      } finally {
        if (!cancelled) setLoading(false);
      }
    }, 200);
    return () => {
      cancelled = true;
      controller.abort();
      window.clearTimeout(timer);
    };
  }, [open, query]);
  React.useEffect(() => {
    if (!open || !value || value.kind === "unknown") {
      setDeals([]);
      return;
    }
    const controller = new AbortController();
    let cancelled = false;
    fetchDealsForEntity({ id: value.id, kind: value.kind }, controller.signal).then((items) => {
      if (!cancelled) setDeals(items);
    }).catch(() => {
      if (!cancelled) setDeals([]);
    });
    return () => {
      cancelled = true;
      controller.abort();
    };
  }, [open, value]);
  const kindLabel = (kind) => kind === "person" ? t("customers.deals.detail.tabs.peopleSingular", "Person") : t("customers.deals.detail.tabs.companySingular", "Company");
  return /* @__PURE__ */ jsxs(
    "div",
    {
      ref: rootRef,
      className: "relative w-full",
      onBlur: (event) => {
        if (!event.currentTarget.contains(event.relatedTarget)) setOpen(false);
      },
      children: [
        /* @__PURE__ */ jsxs(
          "div",
          {
            className: cn(
              "flex h-10 w-full items-center rounded-md bg-background pl-2.5 pr-3 transition-colors hover:bg-accent/50",
              error ? "border border-status-error-border" : CONTROL_BORDER
            ),
            children: [
              /* @__PURE__ */ jsxs(
                Button,
                {
                  type: "button",
                  variant: "ghost",
                  "aria-haspopup": "listbox",
                  "aria-expanded": open,
                  "aria-label": label,
                  onClick: () => setOpen((previous) => !previous),
                  className: "h-full min-w-0 flex-1 justify-between rounded-none bg-transparent p-0 text-left shadow-none hover:bg-transparent dark:hover:bg-transparent",
                  children: [
                    /* @__PURE__ */ jsx("span", { className: "flex min-w-0 items-center gap-2", children: value ? /* @__PURE__ */ jsx(
                      PersonChip,
                      {
                        compact: true,
                        name: value.label || value.id
                      }
                    ) : /* @__PURE__ */ jsx("span", { className: "truncate text-sm text-muted-foreground", children: t("customers.calendar.editor.relatedToPlaceholder", "Search people or companies\u2026") }) }),
                    /* @__PURE__ */ jsxs("span", { className: "flex shrink-0 items-center", children: [
                      deal ? /* @__PURE__ */ jsx(UppercaseBadge, { className: "h-7 bg-status-info-bg text-status-info-text", children: t("customers.calendar.editor.dealBadge", "{name} \xB7 Deal", { name: deal.label }) }) : null,
                      /* @__PURE__ */ jsx("span", { "aria-hidden": true, className: "h-px w-2" }),
                      /* @__PURE__ */ jsx(ChevronDown, { "aria-hidden": true, className: "size-4 opacity-60" })
                    ] })
                  ]
                }
              ),
              value ? /* @__PURE__ */ jsx(
                IconButton,
                {
                  variant: "ghost",
                  size: "xs",
                  onClick: () => {
                    onChange(null);
                    onDealChange(null);
                  },
                  "aria-label": t("customers.calendar.editor.removeRelated", "Clear related record"),
                  className: "ms-1 shrink-0 text-muted-foreground",
                  children: /* @__PURE__ */ jsx(X, { "aria-hidden": true, className: "size-3.5" })
                }
              ) : null
            ]
          }
        ),
        open ? /* @__PURE__ */ jsxs("div", { role: "listbox", "aria-label": label, className: DROPDOWN_PANEL_CLASS, children: [
          /* @__PURE__ */ jsx(
            Input,
            {
              type: "text",
              value: query,
              onChange: (event) => setQuery(event.target.value),
              placeholder: t("customers.calendar.editor.relatedToPlaceholder", "Search people or companies\u2026"),
              "aria-label": t("customers.calendar.editor.relatedToPlaceholder", "Search people or companies\u2026"),
              autoFocus: true,
              size: "sm",
              className: "mb-1"
            }
          ),
          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 && options.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 ? options.map((option) => /* @__PURE__ */ jsxs(
            Button,
            {
              type: "button",
              variant: "ghost",
              role: "option",
              "aria-selected": value?.id === option.id,
              "aria-label": composeAccessibleName([option.label, option.subtitle, kindLabel(option.kind)]),
              title: composeAccessibleName([option.label, option.subtitle]),
              onClick: () => {
                onChange({ id: option.id, kind: option.kind, label: option.label });
                if (value?.id !== option.id) onDealChange(null);
                setQuery("");
              },
              className: OPTION_ROW_CLASS,
              children: [
                option.kind === "company" ? /* @__PURE__ */ jsx(Building2, { "aria-hidden": true, className: "size-3.5 shrink-0 text-muted-foreground" }) : /* @__PURE__ */ jsx(User, { "aria-hidden": true, className: "size-3.5 shrink-0 text-muted-foreground" }),
                /* @__PURE__ */ jsxs("span", { className: "min-w-0 flex-1 truncate", children: [
                  option.label,
                  option.subtitle ? /* @__PURE__ */ jsx("span", { className: "ml-1.5 text-xs text-muted-foreground", children: option.subtitle }) : null
                ] }),
                /* @__PURE__ */ jsx("span", { className: "shrink-0 text-xs text-muted-foreground", children: kindLabel(option.kind) })
              ]
            },
            `${option.kind}:${option.id}`
          )) : null,
          value && deals.length > 0 ? /* @__PURE__ */ jsxs(Fragment, { children: [
            /* @__PURE__ */ jsx("p", { className: "px-2 pb-1 pt-2 text-overline font-medium uppercase text-muted-foreground", children: t("customers.calendar.editor.dealsSection", "Deals") }),
            /* @__PURE__ */ jsx(
              Button,
              {
                type: "button",
                variant: "ghost",
                role: "option",
                "aria-selected": deal === null,
                onClick: () => {
                  onDealChange(null);
                  setOpen(false);
                },
                className: OPTION_ROW_CLASS,
                children: t("customers.calendar.editor.dealNone", "No deal")
              }
            ),
            deals.map((option) => /* @__PURE__ */ jsxs(
              Button,
              {
                type: "button",
                variant: "ghost",
                role: "option",
                "aria-selected": deal?.id === option.id,
                title: option.label,
                onClick: () => {
                  onDealChange(option);
                  setOpen(false);
                },
                className: OPTION_ROW_CLASS,
                children: [
                  /* @__PURE__ */ jsx("span", { className: "min-w-0 flex-1 truncate", children: option.label }),
                  /* @__PURE__ */ jsx(UppercaseBadge, { className: "bg-status-info-bg text-status-info-text", children: t("customers.calendar.editor.dealBadgeSuffix", "Deal") })
                ]
              },
              option.id
            ))
          ] }) : null
        ] }) : null
      ]
    }
  );
}
export {
  RelatedToField
};
//# sourceMappingURL=RelatedToField.js.map
