"use client";
import { jsx, jsxs } from "react/jsx-runtime";
import * as React from "react";
import { Undo2, Plus } from "lucide-react";
import { Button } from "@open-mercato/ui/primitives/button";
import { Badge } from "@open-mercato/ui/primitives/badge";
import { ErrorMessage, LoadingMessage, TabEmptyState } from "@open-mercato/ui/backend/detail";
import { apiCall, withScopedApiRequestHeaders } from "@open-mercato/ui/backend/utils/apiCall";
import { buildOptimisticLockHeader } from "@open-mercato/ui/backend/utils/optimisticLock";
import { deleteCrud } from "@open-mercato/ui/backend/utils/crud";
import { flash } from "@open-mercato/ui/backend/FlashMessages";
import { RowActions } from "@open-mercato/ui/backend/RowActions";
import { useConfirmDialog } from "@open-mercato/ui/backend/confirm-dialog";
import { useOrganizationScopeDetail } from "@open-mercato/shared/lib/frontend/useOrganizationScope";
import { useT } from "@open-mercato/shared/lib/i18n/context";
import {
  emitSalesDocumentTotalsRefresh,
  subscribeSalesDocumentTotalsRefresh
} from "@open-mercato/core/modules/sales/lib/frontend/documentTotalsEvents";
import { sumShippedQuantityByLine } from "@open-mercato/core/modules/sales/lib/returnQuantity";
import { formatMoney, normalizeNumber } from "./lineItemUtils.js";
import { ReturnDialog } from "./ReturnDialog.js";
import { ReturnEditDialog } from "./ReturnEditDialog.js";
import { handleSectionMutationError, readRowUpdatedAt, rowOptimisticVersion } from "./optimisticLock.js";
function formatDisplayDate(value) {
  if (!value) return null;
  const date = new Date(value);
  if (Number.isNaN(date.getTime())) return null;
  return new Intl.DateTimeFormat(void 0, { dateStyle: "medium" }).format(date);
}
function SalesReturnsSection({ orderId, currencyCode, documentUpdatedAt }) {
  const t = useT();
  const { organizationId, tenantId } = useOrganizationScopeDetail();
  const { confirm, ConfirmDialogElement } = useConfirmDialog();
  const [returns, setReturns] = React.useState([]);
  const [lines, setLines] = React.useState([]);
  const [loading, setLoading] = React.useState(false);
  const [error, setError] = React.useState(null);
  const [dialogOpen, setDialogOpen] = React.useState(false);
  const [editRecord, setEditRecord] = React.useState(null);
  const loadLines = React.useCallback(async () => {
    const params = new URLSearchParams({ page: "1", pageSize: "100", orderId });
    const shipmentParams = new URLSearchParams({ page: "1", pageSize: "200", orderId });
    const [response, shipmentsResponse] = await Promise.all([
      apiCall(
        `/api/sales/order-lines?${params.toString()}`,
        void 0,
        { fallback: { items: [] } }
      ),
      apiCall(
        `/api/sales/shipments?${shipmentParams.toString()}`,
        void 0,
        { fallback: { items: [] } }
      )
    ]);
    const shippedByLine = sumShippedQuantityByLine(
      Array.isArray(shipmentsResponse.result?.items) ? shipmentsResponse.result?.items : []
    );
    const items = Array.isArray(response.result?.items) ? response.result?.items ?? [] : [];
    const mapped = items.map((item) => {
      const map = item;
      const id = typeof map.id === "string" ? map.id : null;
      if (!id) return null;
      const snapshot = map["catalog_snapshot"];
      const snapshotName = snapshot && typeof snapshot === "object" && !Array.isArray(snapshot) ? snapshot["name"] : null;
      const name = typeof map.name === "string" ? map.name : typeof snapshotName === "string" ? snapshotName : null;
      const lineNumber = typeof map["line_number"] === "number" ? map["line_number"] : typeof map.lineNumber === "number" ? map.lineNumber : null;
      const quantity = typeof map.quantity === "number" ? map.quantity : typeof map.quantity === "string" ? Number(map.quantity) : 0;
      const returnedQuantity = typeof map["returned_quantity"] === "number" ? map["returned_quantity"] : typeof map.returnedQuantity === "number" ? map.returnedQuantity : typeof map["returned_quantity"] === "string" ? Number(map["returned_quantity"]) : typeof map.returnedQuantity === "string" ? Number(map.returnedQuantity) : 0;
      return {
        id,
        title: name ?? id,
        lineNumber,
        quantity: Number.isFinite(quantity) ? quantity : 0,
        returnedQuantity: Number.isFinite(returnedQuantity) ? returnedQuantity : 0,
        shippedQuantity: shippedByLine.get(id) ?? 0
      };
    }).filter((entry) => Boolean(entry?.id));
    setLines(mapped);
  }, [orderId]);
  const loadReturns = React.useCallback(async () => {
    setLoading(true);
    setError(null);
    try {
      const params = new URLSearchParams({ page: "1", pageSize: "100", orderId });
      const response = await apiCall(
        `/api/sales/returns?${params.toString()}`,
        void 0,
        { fallback: { items: [] } }
      );
      const items = Array.isArray(response.result?.items) ? response.result?.items ?? [] : [];
      const mapped = items.map((item) => {
        const map = item;
        const id = typeof map.id === "string" ? map.id : null;
        if (!id) return null;
        const returnNumber = typeof map["return_number"] === "string" ? map["return_number"] : typeof map.returnNumber === "string" ? map.returnNumber : id;
        const returnedAt = typeof map["returned_at"] === "string" ? map["returned_at"] : typeof map.returnedAt === "string" ? map.returnedAt : null;
        const totalNetAmount = typeof map["total_net_amount"] === "number" ? map["total_net_amount"] : typeof map.totalNetAmount === "number" ? map.totalNetAmount : null;
        const totalGrossAmount = typeof map["total_gross_amount"] === "number" ? map["total_gross_amount"] : typeof map.totalGrossAmount === "number" ? map.totalGrossAmount : null;
        const reason = typeof map.reason === "string" ? map.reason : null;
        const notes = typeof map.notes === "string" ? map.notes : null;
        return {
          id,
          returnNumber,
          status: typeof map.status === "string" ? map.status : null,
          reason,
          notes,
          returnedAt,
          updatedAt: readRowUpdatedAt(map),
          totalNetAmount,
          totalGrossAmount
        };
      }).filter((entry) => Boolean(entry?.id));
      setReturns(mapped);
      await loadLines();
    } catch {
      setError(t("sales.returns.errors.load", "Failed to load returns."));
    } finally {
      setLoading(false);
    }
  }, [loadLines, orderId, t]);
  React.useEffect(() => {
    loadReturns();
  }, [loadReturns]);
  React.useEffect(() => {
    return subscribeSalesDocumentTotalsRefresh((detail) => {
      if (detail.documentId !== orderId) return;
      loadReturns();
    });
  }, [loadReturns, orderId]);
  const emptyState = React.useMemo(
    () => ({
      title: t("sales.returns.empty.title", "No returns yet."),
      description: t("sales.returns.empty.description", "Create a return to generate credit adjustments for returned items.")
    }),
    [t]
  );
  const rows = React.useMemo(() => {
    return returns.map((ret) => {
      const total = normalizeNumber(ret.totalGrossAmount ?? ret.totalNetAmount ?? 0, 0);
      return {
        ...ret,
        total
      };
    });
  }, [returns]);
  const handleEdit = React.useCallback((row) => {
    setEditRecord({
      id: row.id,
      reason: row.reason,
      notes: row.notes,
      returnedAt: row.returnedAt,
      updatedAt: row.updatedAt
    });
  }, []);
  const handleDelete = React.useCallback(
    async (row) => {
      const confirmed = await confirm({
        title: t("sales.returns.confirmDelete", "Delete this return?"),
        description: t(
          "sales.returns.confirmDelete.description",
          "This reverses the returned quantities and the related credit adjustments."
        ),
        variant: "destructive"
      });
      if (!confirmed) return;
      try {
        const result = await withScopedApiRequestHeaders(
          buildOptimisticLockHeader(rowOptimisticVersion(row)),
          () => deleteCrud("sales/returns", {
            body: {
              id: row.id,
              orderId,
              ...organizationId ? { organizationId } : {},
              ...tenantId ? { tenantId } : {}
            },
            errorMessage: t("sales.returns.errors.delete", "Failed to delete return.")
          })
        );
        if (result.ok) {
          emitSalesDocumentTotalsRefresh({ documentId: orderId, kind: "order" });
          await loadReturns();
        }
      } catch (err) {
        if (handleSectionMutationError(err, t, () => void loadReturns())) return;
        flash(t("sales.returns.errors.delete", "Failed to delete return."), "error");
      }
    },
    [confirm, loadReturns, orderId, organizationId, tenantId, t]
  );
  if (loading) return /* @__PURE__ */ jsx(LoadingMessage, { label: t("sales.returns.loading", "Loading returns\u2026") });
  if (error) return /* @__PURE__ */ jsx(ErrorMessage, { label: error });
  if (!rows.length) {
    return /* @__PURE__ */ jsxs("div", { className: "space-y-4", children: [
      /* @__PURE__ */ jsx(
        TabEmptyState,
        {
          title: emptyState.title,
          description: emptyState.description,
          action: {
            label: t("sales.returns.create", "Create return"),
            icon: /* @__PURE__ */ jsx(Plus, { className: "mr-2 h-4 w-4", "aria-hidden": true }),
            onClick: () => setDialogOpen(true)
          }
        }
      ),
      /* @__PURE__ */ jsx(
        ReturnDialog,
        {
          open: dialogOpen,
          orderId,
          lines,
          documentUpdatedAt,
          onClose: () => setDialogOpen(false),
          onSaved: async () => {
            emitSalesDocumentTotalsRefresh({ documentId: orderId, kind: "order" });
            await loadReturns();
          }
        }
      )
    ] });
  }
  return /* @__PURE__ */ jsxs("div", { className: "space-y-4", children: [
    /* @__PURE__ */ jsx("div", { className: "flex items-center justify-end", children: /* @__PURE__ */ jsxs(Button, { type: "button", onClick: () => setDialogOpen(true), children: [
      /* @__PURE__ */ jsx(Plus, { className: "mr-2 h-4 w-4", "aria-hidden": true }),
      t("sales.returns.create", "Create return")
    ] }) }),
    /* @__PURE__ */ jsxs("div", { className: "overflow-hidden rounded-md border", children: [
      /* @__PURE__ */ jsxs("div", { className: "grid grid-cols-[1fr_auto_auto_auto] gap-3 border-b bg-muted/30 px-4 py-2 text-xs font-medium text-muted-foreground", children: [
        /* @__PURE__ */ jsx("div", { children: t("sales.returns.returnNumber", "Return") }),
        /* @__PURE__ */ jsx("div", { className: "text-right", children: t("sales.returns.returnedAt", "Returned at") }),
        /* @__PURE__ */ jsx("div", { className: "text-right", children: t("sales.returns.total", "Total") }),
        /* @__PURE__ */ jsx("div", { className: "sr-only", children: t("sales.returns.actions", "Actions") })
      ] }),
      /* @__PURE__ */ jsx("div", { className: "divide-y", children: rows.map((ret) => /* @__PURE__ */ jsxs("div", { className: "grid grid-cols-[1fr_auto_auto_auto] items-center gap-3 px-4 py-3", children: [
        /* @__PURE__ */ jsx("div", { className: "min-w-0", children: /* @__PURE__ */ jsxs("div", { className: "flex items-center gap-2", children: [
          /* @__PURE__ */ jsx(Undo2, { className: "h-4 w-4 text-muted-foreground", "aria-hidden": true }),
          /* @__PURE__ */ jsx("div", { className: "truncate text-sm font-medium", children: ret.returnNumber }),
          ret.status ? /* @__PURE__ */ jsx(Badge, { variant: "secondary", children: ret.status }) : null
        ] }) }),
        /* @__PURE__ */ jsx("div", { className: "whitespace-nowrap text-right text-sm text-muted-foreground", children: formatDisplayDate(ret.returnedAt) ?? t("sales.returns.notSet", "Not set") }),
        /* @__PURE__ */ jsx("div", { className: "whitespace-nowrap text-right text-sm font-medium", children: formatMoney(ret.total, currencyCode ?? null) }),
        /* @__PURE__ */ jsx("div", { className: "flex justify-end", children: /* @__PURE__ */ jsx(
          RowActions,
          {
            items: [
              {
                id: "edit",
                label: t("ui.actions.edit", "Edit"),
                onSelect: () => handleEdit(ret)
              },
              {
                id: "delete",
                label: t("ui.actions.delete", "Delete"),
                destructive: true,
                onSelect: () => void handleDelete(ret)
              }
            ]
          }
        ) })
      ] }, ret.id)) })
    ] }),
    /* @__PURE__ */ jsx(
      ReturnDialog,
      {
        open: dialogOpen,
        orderId,
        lines,
        documentUpdatedAt,
        onClose: () => setDialogOpen(false),
        onSaved: async () => {
          emitSalesDocumentTotalsRefresh({ documentId: orderId, kind: "order" });
          await loadReturns();
        }
      }
    ),
    /* @__PURE__ */ jsx(
      ReturnEditDialog,
      {
        open: editRecord !== null,
        returnRecord: editRecord,
        orderId,
        organizationId: organizationId ?? null,
        tenantId: tenantId ?? null,
        onClose: () => setEditRecord(null),
        onSaved: async () => {
          setEditRecord(null);
          emitSalesDocumentTotalsRefresh({ documentId: orderId, kind: "order" });
          await loadReturns();
        }
      }
    ),
    ConfirmDialogElement
  ] });
}
export {
  SalesReturnsSection
};
//# sourceMappingURL=ReturnsSection.js.map
