"use client";
import { jsx, jsxs } from "react/jsx-runtime";
import * as React from "react";
import Link from "next/link";
import { apiCall } from "@open-mercato/ui/backend/utils/apiCall";
import { Input } from "@open-mercato/ui/primitives/input";
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue
} from "@open-mercato/ui/primitives/select";
import { Spinner } from "@open-mercato/ui/primitives/spinner";
import { Badge } from "@open-mercato/ui/primitives/badge";
import { formatRelativeTime } from "@open-mercato/shared/lib/time";
import { useT } from "@open-mercato/shared/lib/i18n/context";
import { DEFAULT_SETTINGS, hydrateSalesNewQuotesSettings } from "./config.js";
import { readString, toDateInputValue, openNativeDatePicker, formatAmount } from "../shared.js";
import { createLogger } from "@open-mercato/shared/lib/logger";
const logger = createLogger("sales");
function parseNewQuoteItems(payload) {
  const rawItems = Array.isArray(payload?.items) ? payload?.items : [];
  return rawItems.map((item) => {
    if (!item || typeof item !== "object") return null;
    const data = item;
    const id = readString(data.id);
    const quoteNumber = readString(data.quoteNumber);
    const createdAt = readString(data.createdAt);
    if (!id || !quoteNumber || !createdAt) return null;
    return {
      id,
      quoteNumber,
      status: readString(data.status),
      customerName: readString(data.customerName),
      customerEntityId: readString(data.customerEntityId),
      netAmount: readString(data.netAmount) ?? "0",
      grossAmount: readString(data.grossAmount) ?? "0",
      currency: readString(data.currency),
      createdAt,
      validFrom: readString(data.validFrom),
      validUntil: readString(data.validUntil),
      convertedOrderId: readString(data.convertedOrderId)
    };
  }).filter((item) => !!item);
}
async function loadNewQuotes(settings) {
  const params = new URLSearchParams({
    limit: String(settings.pageSize),
    datePeriod: settings.datePeriod
  });
  if (settings.datePeriod === "custom") {
    if (settings.customFrom) params.set("customFrom", settings.customFrom);
    if (settings.customTo) params.set("customTo", settings.customTo);
  }
  const call = await apiCall(`/api/sales/dashboard/widgets/new-quotes?${params.toString()}`);
  if (!call.ok) {
    const message = typeof call.result?.error === "string" ? call.result.error : `Request failed with status ${call.status}`;
    throw new Error(message);
  }
  return parseNewQuoteItems(call.result ?? null);
}
function resolveDetailHref(item) {
  return item.id ? `/backend/sales/quotes/${encodeURIComponent(item.id)}` : null;
}
const SalesNewQuotesWidget = ({
  mode,
  settings = DEFAULT_SETTINGS,
  onSettingsChange,
  refreshToken,
  onRefreshStateChange
}) => {
  const translate = useT();
  const hydrated = React.useMemo(() => hydrateSalesNewQuotesSettings(settings), [settings]);
  const [items, setItems] = React.useState([]);
  const [loading, setLoading] = React.useState(true);
  const [error, setError] = React.useState(null);
  const [locale, setLocale] = React.useState(void 0);
  React.useEffect(() => {
    if (typeof navigator !== "undefined") {
      setLocale(navigator.language);
    }
  }, []);
  const refresh = React.useCallback(async () => {
    onRefreshStateChange?.(true);
    setLoading(true);
    setError(null);
    try {
      const data = await loadNewQuotes(hydrated);
      setItems(data);
    } catch (err) {
      logger.error("Failed to load new quotes widget data", { err });
      setError(translate("sales.widgets.newQuotes.error", "Failed to load quotes"));
    } finally {
      setLoading(false);
      onRefreshStateChange?.(false);
    }
  }, [hydrated, onRefreshStateChange, translate]);
  React.useEffect(() => {
    refresh().catch(() => {
    });
  }, [refresh, refreshToken]);
  if (mode === "settings") {
    return /* @__PURE__ */ jsxs("div", { className: "space-y-4 text-sm", children: [
      /* @__PURE__ */ jsxs("div", { className: "space-y-1.5", children: [
        /* @__PURE__ */ jsx("label", { htmlFor: "sales-new-quotes-page-size", className: "text-xs font-semibold uppercase text-muted-foreground", children: translate("sales.widgets.newQuotes.settings.pageSize", "Number of Quotes") }),
        /* @__PURE__ */ jsx(
          Input,
          {
            id: "sales-new-quotes-page-size",
            type: "number",
            min: 1,
            max: 20,
            className: "w-24",
            value: hydrated.pageSize,
            onChange: (event) => {
              const next = Number(event.target.value);
              if (!Number.isFinite(next)) return;
              const clamped = Math.min(20, Math.max(1, Math.floor(next)));
              onSettingsChange?.({ ...hydrated, pageSize: clamped });
            }
          }
        )
      ] }),
      /* @__PURE__ */ jsxs("div", { className: "space-y-1.5", children: [
        /* @__PURE__ */ jsx("label", { htmlFor: "sales-new-quotes-date-period", className: "text-xs font-semibold uppercase text-muted-foreground", children: translate("sales.widgets.newQuotes.settings.datePeriod", "Date Period") }),
        /* @__PURE__ */ jsxs(
          Select,
          {
            value: hydrated.datePeriod,
            onValueChange: (value) => {
              onSettingsChange?.({ ...hydrated, datePeriod: value });
            },
            children: [
              /* @__PURE__ */ jsx(SelectTrigger, { id: "sales-new-quotes-date-period", size: "sm", children: /* @__PURE__ */ jsx(SelectValue, {}) }),
              /* @__PURE__ */ jsxs(SelectContent, { children: [
                /* @__PURE__ */ jsx(SelectItem, { value: "last24h", children: translate("sales.widgets.newQuotes.settings.last24h", "Last 24 hours") }),
                /* @__PURE__ */ jsx(SelectItem, { value: "last7d", children: translate("sales.widgets.newQuotes.settings.last7d", "Last 7 days") }),
                /* @__PURE__ */ jsx(SelectItem, { value: "last30d", children: translate("sales.widgets.newQuotes.settings.last30d", "Last 30 days") }),
                /* @__PURE__ */ jsx(SelectItem, { value: "custom", children: translate("sales.widgets.newQuotes.settings.custom", "Custom range") })
              ] })
            ]
          }
        )
      ] }),
      hydrated.datePeriod === "custom" ? /* @__PURE__ */ jsxs("div", { className: "grid gap-3", children: [
        /* @__PURE__ */ jsxs("div", { className: "space-y-1.5", children: [
          /* @__PURE__ */ jsx("label", { htmlFor: "sales-new-quotes-custom-from", className: "text-xs font-semibold uppercase text-muted-foreground", children: translate("sales.widgets.newQuotes.settings.customFrom", "From") }),
          /* @__PURE__ */ jsx(
            "input",
            {
              id: "sales-new-quotes-custom-from",
              type: "date",
              value: toDateInputValue(hydrated.customFrom),
              onChange: (event) => {
                onSettingsChange?.({ ...hydrated, customFrom: event.target.value });
              },
              onFocus: openNativeDatePicker,
              onClick: openNativeDatePicker,
              className: "w-full rounded-md border border-input bg-background px-2 py-1 text-sm text-foreground focus-visible:border-ring focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring"
            }
          )
        ] }),
        /* @__PURE__ */ jsxs("div", { className: "space-y-1.5", children: [
          /* @__PURE__ */ jsx("label", { htmlFor: "sales-new-quotes-custom-to", className: "text-xs font-semibold uppercase text-muted-foreground", children: translate("sales.widgets.newQuotes.settings.customTo", "To") }),
          /* @__PURE__ */ jsx(
            "input",
            {
              id: "sales-new-quotes-custom-to",
              type: "date",
              value: toDateInputValue(hydrated.customTo),
              onChange: (event) => {
                onSettingsChange?.({ ...hydrated, customTo: event.target.value });
              },
              onFocus: openNativeDatePicker,
              onClick: openNativeDatePicker,
              className: "w-full rounded-md border border-input bg-background px-2 py-1 text-sm text-foreground focus-visible:border-ring focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring"
            }
          )
        ] })
      ] }) : null
    ] });
  }
  if (error) {
    return /* @__PURE__ */ jsx("p", { className: "text-sm text-destructive", children: error });
  }
  if (loading) {
    return /* @__PURE__ */ jsx("div", { className: "flex h-32 items-center justify-center", children: /* @__PURE__ */ jsx(Spinner, { className: "h-6 w-6 text-muted-foreground" }) });
  }
  if (!items.length) {
    return /* @__PURE__ */ jsx("p", { className: "text-sm text-muted-foreground", children: translate("sales.widgets.newQuotes.empty", "No quotes found") });
  }
  return /* @__PURE__ */ jsx("ul", { className: "space-y-3", children: items.map((item) => {
    const detailHref = resolveDetailHref(item);
    const amountLabel = formatAmount(item.grossAmount, item.currency, locale);
    const createdLabel = formatRelativeTime(item.createdAt) ?? "";
    return /* @__PURE__ */ jsx("li", { className: "rounded-md border p-3", children: /* @__PURE__ */ jsxs("div", { className: "flex items-start justify-between gap-3", children: [
      /* @__PURE__ */ jsxs("div", { className: "space-y-1", children: [
        /* @__PURE__ */ jsxs("div", { className: "flex items-center gap-2", children: [
          detailHref ? /* @__PURE__ */ jsx(Link, { href: detailHref, className: "text-sm font-semibold text-foreground hover:underline", children: item.quoteNumber }) : /* @__PURE__ */ jsx("span", { className: "text-sm font-semibold text-foreground", children: item.quoteNumber }),
          item.status ? /* @__PURE__ */ jsx(Badge, { variant: "outline", className: "text-xs", children: item.status }) : null
        ] }),
        /* @__PURE__ */ jsx("p", { className: "text-xs text-muted-foreground", children: item.customerName ?? translate("sales.widgets.newQuotes.noCustomer", "No customer") }),
        /* @__PURE__ */ jsx("p", { className: "text-xs text-muted-foreground", children: createdLabel })
      ] }),
      /* @__PURE__ */ jsx("div", { className: "text-right", children: /* @__PURE__ */ jsx("p", { className: "text-sm font-semibold", children: amountLabel }) })
    ] }) }, item.id);
  }) });
};
var widget_client_default = SalesNewQuotesWidget;
export {
  widget_client_default as default
};
//# sourceMappingURL=widget.client.js.map
