"use client";
import { jsx, jsxs } from "react/jsx-runtime";
import * as React from "react";
import { useWidgetData } from "@open-mercato/ui/backend/dashboard/widgetData";
import { useT } from "@open-mercato/shared/lib/i18n/context";
import { TopNTable } from "@open-mercato/ui/backend/charts";
import { DateRangeSelect } from "@open-mercato/ui/backend/date-range";
import { Input } from "@open-mercato/ui/primitives/input";
import { DEFAULT_SETTINGS, hydrateSettings } from "./config.js";
import { formatCurrencySafe } from "../../../lib/formatters.js";
import { createLogger } from "@open-mercato/shared/lib/logger";
const logger = createLogger("dashboards").child({ component: "top-customers" });
async function fetchTopCustomersData(settings, fetchWidgetData) {
  const body = {
    entityType: "sales:orders",
    metric: {
      field: "grandTotalGrossAmount",
      aggregate: "sum"
    },
    groupBy: {
      field: "customerEntityId",
      limit: settings.limit,
      resolveLabels: true
    },
    dateRange: {
      field: "placedAt",
      preset: settings.dateRange
    }
  };
  return fetchWidgetData(body);
}
function formatCustomerName(name, unknownLabel) {
  if (!name) return unknownLabel;
  return name;
}
const TopCustomersWidget = ({
  mode,
  settings = DEFAULT_SETTINGS,
  onSettingsChange,
  refreshToken,
  onRefreshStateChange
}) => {
  const t = useT();
  const hydrated = React.useMemo(() => hydrateSettings(settings), [settings]);
  const [data, setData] = React.useState([]);
  const [loading, setLoading] = React.useState(true);
  const [error, setError] = React.useState(null);
  const unknownLabel = t("dashboards.analytics.labels.unknown", "Unknown");
  const columns = React.useMemo(
    () => [
      {
        key: "rank",
        header: "#",
        width: "40px"
      },
      {
        key: "customerId",
        header: t("dashboards.analytics.widgets.topCustomers.column.customer", "Customer"),
        formatter: (value) => formatCustomerName(String(value || ""), unknownLabel)
      },
      {
        key: "revenue",
        header: t("dashboards.analytics.widgets.topCustomers.column.revenue", "Revenue"),
        align: "right",
        formatter: (value) => formatCurrencySafe(value)
      }
    ],
    [t, unknownLabel]
  );
  const fetchWidgetData = useWidgetData();
  const refresh = React.useCallback(async () => {
    onRefreshStateChange?.(true);
    setLoading(true);
    setError(null);
    try {
      const result = await fetchTopCustomersData(hydrated, fetchWidgetData);
      const tableData = result.data.map((item, index) => ({
        rank: index + 1,
        customerId: item.groupLabel || String(item.groupKey || t("dashboards.analytics.labels.unknown", "Unknown")),
        revenue: item.value ?? 0
      }));
      setData(tableData);
    } catch (err) {
      logger.error("Failed to load top customers data", { err });
      setError(t("dashboards.analytics.widgets.topCustomers.error", "Failed to load data"));
    } finally {
      setLoading(false);
      onRefreshStateChange?.(false);
    }
  }, [hydrated, fetchWidgetData, onRefreshStateChange, t]);
  React.useEffect(() => {
    refresh().catch(() => {
    });
  }, [refresh, refreshToken]);
  if (mode === "settings") {
    return /* @__PURE__ */ jsxs("div", { className: "space-y-4 text-sm", children: [
      /* @__PURE__ */ jsx(
        DateRangeSelect,
        {
          id: "top-customers-date-range",
          label: t("dashboards.analytics.settings.dateRange", "Date Range"),
          value: hydrated.dateRange,
          onChange: (dateRange) => onSettingsChange({ ...hydrated, dateRange })
        }
      ),
      /* @__PURE__ */ jsxs("div", { className: "space-y-1.5", children: [
        /* @__PURE__ */ jsx(
          "label",
          {
            htmlFor: "top-customers-limit",
            className: "text-xs font-semibold uppercase text-muted-foreground",
            children: t("dashboards.analytics.settings.limit", "Number of items")
          }
        ),
        /* @__PURE__ */ jsx(
          Input,
          {
            id: "top-customers-limit",
            type: "number",
            min: 1,
            max: 20,
            className: "w-24",
            value: hydrated.limit,
            onChange: (e) => {
              const next = Number(e.target.value);
              onSettingsChange({ ...hydrated, limit: Number.isFinite(next) ? next : hydrated.limit });
            }
          }
        )
      ] })
    ] });
  }
  return /* @__PURE__ */ jsx(
    TopNTable,
    {
      data,
      columns,
      loading,
      error,
      emptyMessage: t("dashboards.analytics.widgets.topCustomers.empty", "No customer data for this period")
    }
  );
};
var widget_client_default = TopCustomersWidget;
export {
  widget_client_default as default
};
//# sourceMappingURL=widget.client.js.map
