"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 { PieChart } from "@open-mercato/ui/backend/charts";
import {
  DateRangeSelect,
  InlineDateRangeSelect
} from "@open-mercato/ui/backend/date-range";
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue
} from "@open-mercato/ui/primitives/select";
import { DEFAULT_SETTINGS, hydrateSettings } from "./config.js";
import { createLogger } from "@open-mercato/shared/lib/logger";
const logger = createLogger("dashboards").child({ component: "orders-by-status" });
async function fetchOrdersByStatusData(settings, fetchWidgetData) {
  const body = {
    entityType: "sales:orders",
    metric: {
      field: "id",
      aggregate: "count"
    },
    groupBy: {
      field: "status"
    },
    dateRange: {
      field: "placedAt",
      preset: settings.dateRange
    }
  };
  return fetchWidgetData(body);
}
const ORDER_STATUS_KEYS = {
  draft: "dashboards.analytics.orderStatus.draft",
  pending: "dashboards.analytics.orderStatus.pending",
  confirmed: "dashboards.analytics.orderStatus.confirmed",
  processing: "dashboards.analytics.orderStatus.processing",
  shipped: "dashboards.analytics.orderStatus.shipped",
  delivered: "dashboards.analytics.orderStatus.delivered",
  cancelled: "dashboards.analytics.orderStatus.cancelled"
};
function formatStatusLabel(status, t) {
  if (!status) return t("dashboards.analytics.labels.unknown", "Unknown");
  const key = ORDER_STATUS_KEYS[status.toLowerCase()];
  if (key) {
    return t(key, status.replace(/_/g, " ").replace(/\b\w/g, (l) => l.toUpperCase()));
  }
  return status.replace(/_/g, " ").replace(/\b\w/g, (l) => l.toUpperCase());
}
const OrdersByStatusWidget = ({
  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 fetchWidgetData = useWidgetData();
  const refresh = React.useCallback(async () => {
    onRefreshStateChange?.(true);
    setLoading(true);
    setError(null);
    try {
      const result = await fetchOrdersByStatusData(hydrated, fetchWidgetData);
      const chartData = result.data.map((item) => ({
        name: formatStatusLabel(item.groupKey, t),
        value: item.value ?? 0
      }));
      setData(chartData);
    } catch (err) {
      logger.error("Failed to load orders by status data", { err });
      setError(t("dashboards.analytics.widgets.ordersByStatus.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: "orders-by-status-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: "orders-by-status-variant",
            className: "text-xs font-semibold uppercase text-muted-foreground",
            children: t("dashboards.analytics.settings.chartVariant", "Chart Style")
          }
        ),
        /* @__PURE__ */ jsxs(
          Select,
          {
            value: hydrated.variant,
            onValueChange: (value) => onSettingsChange({ ...hydrated, variant: value }),
            children: [
              /* @__PURE__ */ jsx(SelectTrigger, { id: "orders-by-status-variant", size: "sm", children: /* @__PURE__ */ jsx(SelectValue, {}) }),
              /* @__PURE__ */ jsxs(SelectContent, { children: [
                /* @__PURE__ */ jsx(SelectItem, { value: "donut", children: t("dashboards.analytics.chartVariant.donut", "Donut") }),
                /* @__PURE__ */ jsx(SelectItem, { value: "pie", children: t("dashboards.analytics.chartVariant.pie", "Pie") })
              ] })
            ]
          }
        )
      ] })
    ] });
  }
  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(
      PieChart,
      {
        data,
        loading,
        error,
        variant: hydrated.variant,
        colors: ["blue", "emerald", "amber", "rose", "violet", "cyan"],
        emptyMessage: t("dashboards.analytics.widgets.ordersByStatus.empty", "No orders for this period")
      }
    ) })
  ] });
};
var widget_client_default = OrdersByStatusWidget;
export {
  widget_client_default as default
};
//# sourceMappingURL=widget.client.js.map
