"use client";
import { jsx } from "react/jsx-runtime";
import * as React from "react";
import Link from "next/link";
import { useRouter } from "next/navigation";
import { useQuery, keepPreviousData } from "@tanstack/react-query";
import { DataTable } from "@open-mercato/ui/backend/DataTable";
import { RowActions } from "@open-mercato/ui/backend/RowActions";
import { BooleanIcon } from "@open-mercato/ui/backend/ValueIcons";
import { flash } from "@open-mercato/ui/backend/FlashMessages";
import { readApiResultOrThrow } from "@open-mercato/ui/backend/utils/apiCall";
import { Button } from "@open-mercato/ui/primitives/button";
import { useOrganizationScopeVersion } from "@open-mercato/shared/lib/frontend/useOrganizationScope";
import { useT } from "@open-mercato/shared/lib/i18n/context";
import { resolveTodoHref } from "./detail/utils.js";
const TASKS_TAB_QUERY = "tab=tasks";
const CUSTOMER_TASKS_API_PATH = "/api/customers/interactions/tasks";
function buildCustomerHref(item) {
  const customerId = item.customer?.id;
  if (!customerId) return null;
  const kind = (item.customer?.kind ?? "").toLowerCase();
  const base = kind === "company" ? `/backend/customers/companies-v2/${customerId}` : `/backend/customers/people-v2/${customerId}`;
  return `${base}?${TASKS_TAB_QUERY}`;
}
function buildCustomerTasksQueryString(input) {
  const usp = new URLSearchParams({
    page: String(input.page),
    pageSize: String(input.pageSize)
  });
  if (input.search.trim().length > 0) usp.set("search", input.search.trim());
  if (input.all) usp.set("all", "true");
  return usp.toString();
}
function readValueAtPath(record, path) {
  const segments = path.split(".").filter((segment) => segment.length > 0);
  let current = record;
  for (const segment of segments) {
    if (!current || typeof current !== "object") return null;
    current = current[segment];
  }
  return current ?? null;
}
function CustomerTodosTable() {
  const t = useT();
  const router = useRouter();
  const scopeVersion = useOrganizationScopeVersion();
  const [search, setSearch] = React.useState("");
  const [page, setPage] = React.useState(1);
  const [pageSize] = React.useState(50);
  const params = React.useMemo(() => buildCustomerTasksQueryString({
    page,
    pageSize,
    search
  }), [page, pageSize, search]);
  const columns = React.useMemo(() => [
    {
      accessorKey: "customer.displayName",
      header: t("customers.workPlan.customerTodos.table.column.customer"),
      cell: ({ row }) => {
        const name = row.original.customer?.displayName;
        if (!name) return /* @__PURE__ */ jsx("span", { className: "text-muted-foreground", children: "\u2014" });
        const href = buildCustomerHref(row.original);
        if (!href) return name;
        return /* @__PURE__ */ jsx(Link, { href, className: "underline-offset-2 hover:underline", children: name });
      },
      meta: { priority: 1 }
    },
    {
      accessorKey: "todoTitle",
      header: t("customers.workPlan.customerTodos.table.column.todo"),
      cell: ({ row }) => {
        const title = row.original.todoTitle ?? t("customers.workPlan.customerTodos.table.column.todo.unnamed");
        const todoHref = row.original.externalHref ?? resolveTodoHref(row.original.todoSource, row.original.todoId);
        if (!todoHref) return /* @__PURE__ */ jsx("span", { className: "text-muted-foreground", children: title });
        return /* @__PURE__ */ jsx(Link, { href: todoHref, className: "underline-offset-2 hover:underline", children: title });
      },
      meta: { priority: 2 }
    },
    {
      accessorKey: "todoIsDone",
      header: t("customers.workPlan.customerTodos.table.column.done"),
      cell: ({ row }) => /* @__PURE__ */ jsx(BooleanIcon, { value: row.original.todoIsDone === true }),
      meta: { priority: 3 }
    }
  ], [t]);
  const viewExportColumns = React.useMemo(() => {
    return columns.map((col) => {
      const accessorKey = col.accessorKey;
      if (!accessorKey || typeof accessorKey !== "string") return null;
      if (col.meta?.hidden) return null;
      const header = typeof col.header === "string" ? col.header : accessorKey;
      return { field: accessorKey, header };
    }).filter((col) => !!col);
  }, [columns]);
  const buildPreparedExport = React.useCallback((exportRows, exportColumns) => ({
    columns: exportColumns.map((col) => ({ field: col.field, header: col.header })),
    rows: exportRows.map((row) => {
      const record = row;
      return Object.fromEntries(
        exportColumns.map((col) => [col.field, readValueAtPath(record, col.field)])
      );
    })
  }), []);
  const fetchTasks = React.useCallback(async (queryString) => {
    return readApiResultOrThrow(
      `${CUSTOMER_TASKS_API_PATH}?${queryString}`,
      void 0,
      { errorMessage: t("customers.workPlan.customerTodos.table.error.load") }
    );
  }, [t]);
  const { data, isLoading, error, refetch, isFetching } = useQuery({
    queryKey: ["customers-interactions-tasks", params, scopeVersion],
    queryFn: async () => fetchTasks(params),
    placeholderData: keepPreviousData
  });
  const rows = data?.items ?? [];
  const exportConfig = React.useMemo(() => ({
    view: {
      description: t("customers.workPlan.customerTodos.table.export.view"),
      prepare: async () => {
        return {
          prepared: buildPreparedExport(rows, viewExportColumns),
          filename: "customer_todos_view"
        };
      }
    },
    full: {
      description: t("customers.workPlan.customerTodos.table.export.full"),
      prepare: async (_format) => {
        const fullData = await fetchTasks(buildCustomerTasksQueryString({
          page: 1,
          pageSize,
          search,
          all: true
        }));
        return {
          prepared: buildPreparedExport(fullData.items, viewExportColumns),
          filename: "customer_todos_full"
        };
      }
    }
  }), [buildPreparedExport, fetchTasks, pageSize, rows, search, t, viewExportColumns]);
  const handleRefresh = React.useCallback(async () => {
    try {
      await refetch();
      flash(t("customers.workPlan.customerTodos.table.flash.refreshed"), "success");
    } catch (err) {
      const message = err instanceof Error ? err.message : t("customers.workPlan.customerTodos.table.error.load");
      flash(message, "error");
    }
  }, [refetch, t]);
  const handleNavigate = React.useCallback((item) => {
    const href = buildCustomerHref(item);
    if (!href) return;
    router.push(href);
  }, [router]);
  const errorMessage = error ? error instanceof Error ? error.message : t("customers.workPlan.customerTodos.table.error.load") : null;
  const emptyStateMessage = !isLoading && !errorMessage && rows.length === 0 ? search ? t("customers.workPlan.customerTodos.table.state.noMatches") : t("customers.workPlan.customerTodos.table.state.empty") : void 0;
  return /* @__PURE__ */ jsx(
    DataTable,
    {
      title: t("customers.workPlan.customerTodos.table.title"),
      actions: /* @__PURE__ */ jsx(
        Button,
        {
          variant: "outline",
          onClick: () => {
            void handleRefresh();
          },
          disabled: isFetching,
          children: t("customers.workPlan.customerTodos.table.actions.refresh")
        }
      ),
      columns,
      data: rows,
      exporter: exportConfig,
      searchValue: search,
      onSearchChange: (value) => {
        setSearch(value);
        setPage(1);
      },
      perspective: { tableId: "customers.todos.list" },
      rowActions: (row) => {
        const customerLink = buildCustomerHref(row);
        const todoHref = row.externalHref ?? resolveTodoHref(row.todoSource, row.todoId);
        const items = [
          customerLink ? {
            id: "open-customer",
            label: t("customers.workPlan.customerTodos.table.actions.openCustomer"),
            href: customerLink
          } : null,
          todoHref ? {
            id: "open-task",
            label: t("customers.workPlan.customerTodos.table.actions.openTask"),
            href: todoHref
          } : null
        ].filter((item) => !!item);
        if (!items.length) return null;
        return /* @__PURE__ */ jsx(RowActions, { items });
      },
      onRowClick: handleNavigate,
      pagination: {
        page,
        pageSize,
        total: data?.total ?? 0,
        totalPages: data?.totalPages ?? 0,
        onPageChange: setPage
      },
      isLoading,
      error: errorMessage,
      emptyState: emptyStateMessage
    }
  );
}
var CustomerTodosTable_default = CustomerTodosTable;
export {
  CustomerTodosTable,
  CustomerTodosTable_default as default
};
//# sourceMappingURL=CustomerTodosTable.js.map
