"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, useLocale } from "@open-mercato/shared/lib/i18n/context";
import { LineChart } 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 { formatCurrencyCompact } from "../../../lib/formatters.js";
import { createLogger } from "@open-mercato/shared/lib/logger";
const logger = createLogger("dashboards").child({ component: "revenue-trend" });
async function fetchRevenueTrendData(settings, fetchWidgetData) {
  const body = {
    entityType: "sales:orders",
    metric: {
      field: "grandTotalGrossAmount",
      aggregate: "sum"
    },
    groupBy: {
      field: "placedAt",
      granularity: settings.granularity
    },
    dateRange: {
      field: "placedAt",
      preset: settings.dateRange
    }
  };
  return fetchWidgetData(body);
}
function formatDate(dateStr, granularity, locale) {
  if (!dateStr) return "--";
  try {
    const date = new Date(dateStr);
    const localeStr = locale ?? void 0;
    switch (granularity) {
      case "day":
      case "week":
        return date.toLocaleDateString(localeStr, { month: "short", day: "numeric" });
      case "month":
        return date.toLocaleDateString(localeStr, { month: "short", year: "numeric" });
      case "quarter": {
        const quarter = Math.floor(date.getMonth() / 3) + 1;
        return `Q${quarter} ${date.getFullYear()}`;
      }
      case "year":
        return date.toLocaleDateString(localeStr, { year: "numeric" });
      default:
        return date.toLocaleDateString(localeStr, { month: "short", day: "numeric" });
    }
  } catch {
    return String(dateStr);
  }
}
const GRANULARITY_OPTIONS = [
  { value: "day", labelKey: "dashboards.analytics.granularity.day" },
  { value: "week", labelKey: "dashboards.analytics.granularity.week" },
  { value: "month", labelKey: "dashboards.analytics.granularity.month" },
  { value: "quarter", labelKey: "dashboards.analytics.granularity.quarter" },
  { value: "year", labelKey: "dashboards.analytics.granularity.year" }
];
function getAutoGranularity(dateRange) {
  switch (dateRange) {
    case "today":
    case "yesterday":
    case "last_7_days":
      return "day";
    case "this_week":
    case "last_week":
    case "last_30_days":
      return "day";
    case "this_month":
    case "last_month":
    case "last_90_days":
      return "week";
    case "this_quarter":
    case "last_quarter":
      return "week";
    case "this_year":
    case "last_year":
      return "month";
    default:
      return "day";
  }
}
const RevenueTrendWidget = ({
  mode,
  settings = DEFAULT_SETTINGS,
  onSettingsChange,
  refreshToken,
  onRefreshStateChange
}) => {
  const t = useT();
  const locale = useLocale();
  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 fetchRevenueTrendData(hydrated, fetchWidgetData);
      const sortedData = [...result.data].sort((a, b) => {
        const aTime = new Date(a.groupKey || 0).getTime();
        const bTime = new Date(b.groupKey || 0).getTime();
        return aTime - bTime;
      });
      const chartData = sortedData.map((item) => ({
        date: formatDate(item.groupKey, hydrated.granularity, locale),
        Revenue: item.value ?? 0
      }));
      setData(chartData);
    } catch (err) {
      logger.error("Failed to load revenue trend data", { err });
      setError(t("dashboards.analytics.widgets.revenueTrend.error", "Failed to load data"));
    } finally {
      setLoading(false);
      onRefreshStateChange?.(false);
    }
  }, [hydrated, fetchWidgetData, locale, 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: "revenue-trend-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: "revenue-trend-granularity",
            className: "text-xs font-semibold uppercase text-muted-foreground",
            children: t("dashboards.analytics.settings.granularity", "Granularity")
          }
        ),
        /* @__PURE__ */ jsxs(
          Select,
          {
            value: hydrated.granularity,
            onValueChange: (value) => onSettingsChange({ ...hydrated, granularity: value }),
            children: [
              /* @__PURE__ */ jsx(SelectTrigger, { id: "revenue-trend-granularity", size: "sm", children: /* @__PURE__ */ jsx(SelectValue, {}) }),
              /* @__PURE__ */ jsx(SelectContent, { children: GRANULARITY_OPTIONS.map((opt) => /* @__PURE__ */ jsx(SelectItem, { value: opt.value, children: t(opt.labelKey, opt.value) }, opt.value)) })
            ]
          }
        )
      ] }),
      /* @__PURE__ */ jsx("div", { className: "space-y-1.5", children: /* @__PURE__ */ jsxs("label", { className: "flex items-center gap-2 text-sm", children: [
        /* @__PURE__ */ jsx(
          "input",
          {
            type: "checkbox",
            checked: hydrated.showArea,
            onChange: (e) => onSettingsChange({ ...hydrated, showArea: e.target.checked }),
            className: "h-4 w-4 rounded border focus-visible:ring-ring"
          }
        ),
        t("dashboards.analytics.settings.showArea", "Show area fill")
      ] }) })
    ] });
  }
  const effectiveGranularity = hydrated.granularity === "day" ? getAutoGranularity(hydrated.dateRange) : hydrated.granularity;
  return /* @__PURE__ */ jsxs("div", { children: [
    /* @__PURE__ */ jsx("div", { className: "mb-2 flex justify-end", children: /* @__PURE__ */ jsx(
      InlineDateRangeSelect,
      {
        value: hydrated.dateRange,
        onChange: (dateRange) => onSettingsChange({ ...hydrated, dateRange, granularity: getAutoGranularity(dateRange) })
      }
    ) }),
    /* @__PURE__ */ jsx(
      LineChart,
      {
        data,
        index: "date",
        categories: ["Revenue"],
        categoryLabels: { Revenue: t("dashboards.analytics.widgets.topCustomers.column.revenue", "Revenue") },
        loading,
        error,
        showArea: hydrated.showArea,
        valueFormatter: formatCurrencyCompact,
        colors: ["blue"],
        emptyMessage: t("dashboards.analytics.widgets.revenueTrend.empty", "No revenue data for this period")
      }
    )
  ] });
};
var widget_client_default = RevenueTrendWidget;
export {
  widget_client_default as default
};
//# sourceMappingURL=widget.client.js.map
