"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 { BarChart } from "@open-mercato/ui/backend/charts";
import { DateRangeSelect, InlineDateRangeSelect } from "@open-mercato/ui/backend/date-range";
import { Input } from "@open-mercato/ui/primitives/input";
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue
} from "@open-mercato/ui/primitives/select";
import { DEFAULT_SETTINGS, hydrateSettings } from "./config.js";
import { formatCurrencyCompact } from "../../../lib/formatters.js";
import { createLogger } from "@open-mercato/shared/lib/logger";
const logger = createLogger("dashboards").child({ component: "top-products" });
async function fetchTopProductsData(settings, fetchWidgetData) {
  const body = {
    entityType: "sales:order_lines",
    metric: {
      field: "totalGrossAmount",
      aggregate: "sum"
    },
    groupBy: {
      field: "productId",
      limit: settings.limit,
      resolveLabels: true
    },
    dateRange: {
      field: "createdAt",
      preset: settings.dateRange
    }
  };
  return fetchWidgetData(body);
}
function truncateLabel(label, t, maxLength = 20) {
  if (label == null || label === "") return t("dashboards.analytics.labels.unknownProduct", "Unknown Product");
  const labelStr = String(label);
  if (labelStr === "0" || labelStr === "null" || labelStr === "undefined") {
    return t("dashboards.analytics.labels.unknownProduct", "Unknown Product");
  }
  if (/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(labelStr)) {
    return t("dashboards.analytics.labels.unnamedProduct", "Unnamed Product");
  }
  if (labelStr.length <= maxLength) return labelStr;
  return labelStr.slice(0, maxLength - 3) + "...";
}
const TopProductsWidget = ({
  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 fetchingRef = React.useRef(false);
  const fetchWidgetData = useWidgetData();
  const refresh = React.useCallback(async () => {
    if (fetchingRef.current) return;
    fetchingRef.current = true;
    onRefreshStateChange?.(true);
    setLoading(true);
    setError(null);
    try {
      const result = await fetchTopProductsData(hydrated, fetchWidgetData);
      const chartData = result.data.map((item, index) => ({
        name: truncateLabel(item.groupLabel ?? item.groupKey ?? `Product ${index + 1}`, t),
        Revenue: item.value ?? 0
      }));
      setData(chartData);
    } catch (err) {
      logger.error("Failed to load top products data", { err });
      setError(t("dashboards.analytics.widgets.topProducts.error", "Failed to load data"));
    } finally {
      setLoading(false);
      onRefreshStateChange?.(false);
      fetchingRef.current = 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-products-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-products-limit",
            className: "text-xs font-semibold uppercase text-muted-foreground",
            children: t("dashboards.analytics.settings.limit", "Number of items")
          }
        ),
        /* @__PURE__ */ jsx(
          Input,
          {
            id: "top-products-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 });
            }
          }
        )
      ] }),
      /* @__PURE__ */ jsxs("div", { className: "space-y-1.5", children: [
        /* @__PURE__ */ jsx(
          "label",
          {
            htmlFor: "top-products-layout",
            className: "text-xs font-semibold uppercase text-muted-foreground",
            children: t("dashboards.analytics.settings.chartLayout", "Chart Layout")
          }
        ),
        /* @__PURE__ */ jsxs(
          Select,
          {
            value: hydrated.layout,
            onValueChange: (value) => onSettingsChange({ ...hydrated, layout: value }),
            children: [
              /* @__PURE__ */ jsx(SelectTrigger, { id: "top-products-layout", size: "sm", children: /* @__PURE__ */ jsx(SelectValue, {}) }),
              /* @__PURE__ */ jsxs(SelectContent, { children: [
                /* @__PURE__ */ jsx(SelectItem, { value: "horizontal", children: t("dashboards.analytics.settings.horizontal", "Horizontal") }),
                /* @__PURE__ */ jsx(SelectItem, { value: "vertical", children: t("dashboards.analytics.settings.vertical", "Vertical") })
              ] })
            ]
          }
        )
      ] })
    ] });
  }
  return /* @__PURE__ */ jsxs("div", { className: "flex flex-col h-full", children: [
    /* @__PURE__ */ jsx("div", { className: "flex justify-end mb-2", children: /* @__PURE__ */ jsx(
      InlineDateRangeSelect,
      {
        value: hydrated.dateRange,
        onChange: (dateRange) => onSettingsChange({ ...hydrated, dateRange })
      }
    ) }),
    /* @__PURE__ */ jsx("div", { className: "flex-1 min-h-0", children: /* @__PURE__ */ jsx(
      BarChart,
      {
        data,
        index: "name",
        categories: ["Revenue"],
        categoryLabels: { Revenue: t("dashboards.analytics.widgets.topCustomers.column.revenue", "Revenue") },
        loading,
        error,
        layout: hydrated.layout,
        valueFormatter: formatCurrencyCompact,
        colors: ["emerald"],
        showLegend: false,
        emptyMessage: t("dashboards.analytics.widgets.topProducts.empty", "No product sales data for this period")
      }
    ) })
  ] });
};
var widget_client_default = TopProductsWidget;
export {
  widget_client_default as default
};
//# sourceMappingURL=widget.client.js.map
