"use client";
import { Fragment, jsx, jsxs } from "react/jsx-runtime";
import * as React from "react";
import Link from "next/link";
import { Link2 } from "lucide-react";
import { useT } from "@open-mercato/shared/lib/i18n/context";
import { Button } from "@open-mercato/ui/primitives/button";
import { Input } from "@open-mercato/ui/primitives/input";
import { Pagination } from "@open-mercato/ui/primitives/pagination";
import { LinkEntityDialog } from "../linking/LinkEntityDialog.js";
const PAGE_SIZE = 20;
function normalizeText(value) {
  return value.trim().toLowerCase();
}
function applyFilter(items, query) {
  const normalizedQuery = normalizeText(query);
  if (!normalizedQuery.length) return items;
  return items.filter((item) => {
    const label = normalizeText(item.label);
    const subtitle = normalizeText(item.subtitle ?? "");
    return label.includes(normalizedQuery) || subtitle.includes(normalizedQuery);
  });
}
function DealLinkedEntitiesTab({
  entityLabel,
  entityLabelPlural,
  manageLabel,
  searchPlaceholder,
  linkedItems,
  linkedCount,
  selectedIds,
  disabled = false,
  savePending = false,
  hrefBuilder,
  onSaveSelection,
  loadLinkedPage,
  searchEntities,
  fetchEntitiesByIds,
  icon
}) {
  const t = useT();
  const useRemoteLinkedList = typeof loadLinkedPage === "function";
  const [pageSearch, setPageSearch] = React.useState("");
  const [page, setPage] = React.useState(1);
  const [remoteLinkedItems, setRemoteLinkedItems] = React.useState([]);
  const [remoteLinkedTotalPages, setRemoteLinkedTotalPages] = React.useState(1);
  const [remoteLinkedLoading, setRemoteLinkedLoading] = React.useState(false);
  const [dialogOpen, setDialogOpen] = React.useState(false);
  const selectedIdsKey = React.useMemo(() => selectedIds.join("|"), [selectedIds]);
  const refreshRemoteLinkedList = React.useCallback(
    async (options) => {
      if (!useRemoteLinkedList || !loadLinkedPage) return;
      const showLoading = options?.showLoading ?? true;
      if (showLoading) setRemoteLinkedLoading(true);
      try {
        const result = await loadLinkedPage(page, pageSearch);
        setRemoteLinkedItems(result.items);
        setRemoteLinkedTotalPages(result.totalPages);
      } catch {
        setRemoteLinkedItems([]);
        setRemoteLinkedTotalPages(1);
      } finally {
        if (showLoading) setRemoteLinkedLoading(false);
      }
    },
    [loadLinkedPage, page, pageSearch, useRemoteLinkedList]
  );
  React.useEffect(() => {
    if (!useRemoteLinkedList || !loadLinkedPage) return;
    void refreshRemoteLinkedList();
  }, [loadLinkedPage, refreshRemoteLinkedList, useRemoteLinkedList]);
  React.useEffect(() => {
    if (!useRemoteLinkedList || dialogOpen) return;
    void refreshRemoteLinkedList({ showLoading: false });
  }, [dialogOpen, refreshRemoteLinkedList, selectedIdsKey, useRemoteLinkedList]);
  React.useEffect(() => {
    setPage(1);
  }, [pageSearch]);
  const filteredLinkedItems = React.useMemo(
    () => applyFilter(linkedItems, pageSearch),
    [linkedItems, pageSearch]
  );
  const totalPages = Math.max(1, Math.ceil(filteredLinkedItems.length / PAGE_SIZE));
  const currentPage = Math.min(page, totalPages);
  const pagedLinkedItems = React.useMemo(
    () => filteredLinkedItems.slice((currentPage - 1) * PAGE_SIZE, currentPage * PAGE_SIZE),
    [currentPage, filteredLinkedItems]
  );
  const visibleLinkedItems = useRemoteLinkedList ? remoteLinkedItems : pagedLinkedItems;
  const visiblePage = useRemoteLinkedList ? page : currentPage;
  const visibleTotalPages = useRemoteLinkedList ? remoteLinkedTotalPages : totalPages;
  const totalLinkedCount = linkedCount ?? linkedItems.length;
  const adapter = React.useMemo(
    () => ({
      kind: "person",
      dialogTitle: t(
        "customers.deals.detail.linkedEntities.dialogTitleShort",
        "Link {{entity}}",
        { entity: entityLabel.toLowerCase() }
      ),
      dialogSubtitle: t(
        "customers.deals.detail.linkedEntities.dialogSubtitle",
        "Link an existing {{entity}} to this deal",
        { entity: entityLabel.toLowerCase() }
      ),
      sectionLabel: t(
        "customers.deals.detail.linkedEntities.sectionLabel",
        "MATCHING {{entity}}",
        { entity: entityLabelPlural.toUpperCase() }
      ),
      searchPlaceholder: t(
        "customers.deals.detail.linkedEntities.searchAll",
        "Search all {{entity}}\u2026",
        { entity: entityLabelPlural.toLowerCase() }
      ),
      searchEmptyHint: t(
        "customers.deals.detail.linkedEntities.noResults",
        "No matching records found."
      ),
      selectedEmptyHint: t(
        "customers.deals.detail.linkedEntities.noneSelected",
        "No linked records selected."
      ),
      confirmButtonLabel: t(
        "customers.deals.detail.linkedEntities.confirmButton",
        "Link {{entity}}",
        { entity: entityLabel.toLowerCase() }
      ),
      defaultAvatarIcon: icon,
      searchPage: async (query, searchPageIndex) => {
        const result = await searchEntities(query, searchPageIndex);
        return {
          items: result.items.map((item) => ({
            id: item.id,
            label: item.label,
            subtitle: item.subtitle ?? null
          })),
          totalPages: result.totalPages
        };
      },
      fetchByIds: async (ids) => {
        const result = await fetchEntitiesByIds(ids);
        return result.map((item) => ({
          id: item.id,
          label: item.label,
          subtitle: item.subtitle ?? null
        }));
      }
    }),
    [entityLabel, entityLabelPlural, fetchEntitiesByIds, icon, searchEntities, t]
  );
  const handleDialogConfirm = React.useCallback(
    async ({
      nextSelectedIds
    }) => {
      await onSaveSelection(nextSelectedIds);
      if (useRemoteLinkedList) {
        await refreshRemoteLinkedList({ showLoading: false });
      }
    },
    [onSaveSelection, refreshRemoteLinkedList, useRemoteLinkedList]
  );
  return /* @__PURE__ */ jsxs(Fragment, { children: [
    /* @__PURE__ */ jsxs("div", { className: "space-y-5", children: [
      /* @__PURE__ */ jsxs("div", { className: "flex flex-col gap-3 rounded-xl border border-border/70 bg-muted/10 p-4 sm:flex-row sm:items-center sm:justify-between", children: [
        /* @__PURE__ */ jsxs("div", { className: "space-y-1", children: [
          /* @__PURE__ */ jsx("div", { className: "text-sm font-semibold text-foreground", children: manageLabel }),
          /* @__PURE__ */ jsx("div", { className: "text-sm text-muted-foreground", children: t(
            "customers.deals.detail.linkedEntities.summary",
            "{{count}} linked {{entity}}",
            {
              count: totalLinkedCount,
              entity: totalLinkedCount === 1 ? entityLabel.toLowerCase() : entityLabelPlural.toLowerCase()
            }
          ) })
        ] }),
        /* @__PURE__ */ jsxs("div", { className: "flex items-center gap-2", children: [
          /* @__PURE__ */ jsx("div", { className: "relative min-w-0 flex-1 sm:w-[260px]", children: /* @__PURE__ */ jsx(
            Input,
            {
              value: pageSearch,
              onChange: (event) => setPageSearch(event.target.value),
              placeholder: searchPlaceholder
            }
          ) }),
          /* @__PURE__ */ jsxs(
            Button,
            {
              type: "button",
              variant: "outline",
              size: "sm",
              className: "h-9 rounded-lg px-3",
              onClick: () => setDialogOpen(true),
              disabled: disabled || savePending,
              children: [
                /* @__PURE__ */ jsx(Link2, { className: "mr-2 size-4" }),
                t("customers.deals.detail.linkedEntities.manage", "Manage links")
              ]
            }
          )
        ] })
      ] }),
      visibleLinkedItems.length ? /* @__PURE__ */ jsxs("div", { className: "space-y-3", children: [
        visibleLinkedItems.map((item) => /* @__PURE__ */ jsxs(
          Link,
          {
            href: hrefBuilder(item.id),
            className: "flex items-start gap-3 rounded-xl border border-border/70 bg-card px-4 py-4 transition-colors hover:bg-accent",
            children: [
              /* @__PURE__ */ jsx("div", { className: "mt-0.5 rounded-full bg-muted p-2 text-muted-foreground", children: icon }),
              /* @__PURE__ */ jsxs("div", { className: "min-w-0", children: [
                /* @__PURE__ */ jsx("div", { className: "truncate text-sm font-semibold text-foreground", children: item.label }),
                /* @__PURE__ */ jsx("div", { className: "mt-1 text-xs text-muted-foreground", children: item.subtitle || "\u2014" })
              ] })
            ]
          },
          item.id
        )),
        visibleTotalPages > 1 ? /* @__PURE__ */ jsx(
          Pagination,
          {
            className: "border-t border-border/70 pt-3",
            page: visiblePage,
            pageSize: PAGE_SIZE,
            total: visibleTotalPages * PAGE_SIZE,
            onPageChange: setPage
          }
        ) : null
      ] }) : remoteLinkedLoading ? /* @__PURE__ */ jsx("div", { className: "rounded-lg border border-border bg-muted/20 px-5 py-5 text-sm text-muted-foreground", children: t("customers.deals.detail.linkedEntities.loading", "Loading linked records\u2026") }) : /* @__PURE__ */ jsx("div", { className: "rounded-lg border border-border bg-muted/20 px-5 py-5 text-sm text-muted-foreground", children: pageSearch.trim().length ? t(
        "customers.deals.detail.linkedEntities.noSearchMatches",
        "No linked records match the current search."
      ) : t("customers.deals.detail.linkedEntities.empty", "No linked records yet.") })
    ] }),
    /* @__PURE__ */ jsx(
      LinkEntityDialog,
      {
        open: dialogOpen,
        onOpenChange: setDialogOpen,
        adapter,
        initialSelectedIds: selectedIds,
        onConfirm: handleDialogConfirm
      }
    )
  ] });
}
var DealLinkedEntitiesTab_default = DealLinkedEntitiesTab;
export {
  DealLinkedEntitiesTab,
  DealLinkedEntitiesTab_default as default
};
//# sourceMappingURL=DealLinkedEntitiesTab.js.map
