"use client";
import { jsx, jsxs } from "react/jsx-runtime";
import { Button } from "@open-mercato/ui/primitives/button";
import { useT } from "@open-mercato/shared/lib/i18n/context";
import {
  CheckCircle,
  XCircle,
  Pencil,
  AlertTriangle,
  RefreshCw,
  Package,
  FileText,
  MessageSquare,
  Truck,
  UserPlus,
  Link2,
  Activity,
  ShoppingBag
} from "lucide-react";
import { hasContactNameIssue } from "../../lib/contactValidation.js";
function useDiscrepancyDescriptions() {
  const t = useT();
  const translations = {
    "inbox_ops.discrepancy.desc.no_channel": t("inbox_ops.discrepancy.desc.no_channel", "No sales channel available. Create a channel in Sales settings before accepting this order."),
    "inbox_ops.discrepancy.desc.no_currency": t("inbox_ops.discrepancy.desc.no_currency", "No currency could be resolved for this order. Set a currency code or configure a sales channel with a default currency."),
    "inbox_ops.discrepancy.desc.product_not_matched": t("inbox_ops.discrepancy.desc.product_not_matched", "Product could not be matched to any catalog product"),
    "inbox_ops.discrepancy.desc.no_matching_contact": t("inbox_ops.discrepancy.desc.no_matching_contact", "No matching contact found"),
    "inbox_ops.discrepancy.desc.draft_reply_no_contact": t("inbox_ops.discrepancy.desc.draft_reply_no_contact", "Draft reply target has no matching contact. Create the contact first."),
    "inbox_ops.discrepancy.desc.duplicate_order_reference": t("inbox_ops.discrepancy.desc.duplicate_order_reference", "An order with this customer reference already exists")
  };
  return (description, foundValue) => {
    const translated = translations[description];
    if (!translated) return description;
    if (foundValue && (description === "inbox_ops.discrepancy.desc.product_not_matched" || description === "inbox_ops.discrepancy.desc.no_matching_contact")) {
      return `${translated}: ${foundValue}`;
    }
    return translated;
  };
}
function useActionDescriptionResolver() {
  const t = useT();
  return (description, payload) => {
    if (!description.startsWith("inbox_ops.action.desc.")) return description;
    const name = payload.name || payload.contactName || "";
    const email = payload.email || payload.emailAddress || "";
    const title = payload.title || "";
    const toName = payload.toName || payload.to || "";
    const subject = payload.subject || "";
    const translations = {
      "inbox_ops.action.desc.create_contact": t("inbox_ops.action.desc.create_contact", "Create contact for {name} ({email})").replace("{name}", name).replace("{email}", email),
      "inbox_ops.action.desc.link_contact": t("inbox_ops.action.desc.link_contact", "Link {name} ({email}) to existing contact").replace("{name}", name).replace("{email}", email),
      "inbox_ops.action.desc.create_product": t("inbox_ops.action.desc.create_product", 'Create catalog product "{title}"').replace("{title}", title),
      "inbox_ops.action.desc.draft_reply": t("inbox_ops.action.desc.draft_reply", "Draft reply to {toName}: {subject}").replace("{toName}", toName).replace("{subject}", subject)
    };
    return translations[description] || description;
  };
}
const ACTION_TYPE_ICONS = {
  create_order: Package,
  create_quote: FileText,
  update_order: Package,
  update_shipment: Truck,
  create_contact: UserPlus,
  create_product: ShoppingBag,
  link_contact: Link2,
  log_activity: Activity,
  draft_reply: MessageSquare
};
function useActionTypeLabels() {
  const t = useT();
  return {
    create_order: t("inbox_ops.action_type.create_order", "Create Sales Order"),
    create_quote: t("inbox_ops.action_type.create_quote", "Create Quote"),
    update_order: t("inbox_ops.action_type.update_order", "Update Order"),
    update_shipment: t("inbox_ops.action_type.update_shipment", "Update Shipment"),
    create_contact: t("inbox_ops.action_type.create_contact", "Create Contact"),
    create_product: t("inbox_ops.action_type.create_product", "Create Product"),
    link_contact: t("inbox_ops.action_type.link_contact", "Link Contact"),
    log_activity: t("inbox_ops.action_type.log_activity", "Log Activity"),
    draft_reply: t("inbox_ops.action_type.draft_reply", "Draft Reply")
  };
}
function ConfidenceBadge({ value }) {
  const num = parseFloat(value);
  const pct = Math.round(num * 100);
  const color = num >= 0.8 ? "text-status-success-text" : num >= 0.6 ? "text-status-warning-text" : "text-status-error-text";
  const bgColor = num >= 0.8 ? "bg-status-success-icon" : num >= 0.6 ? "bg-status-warning-icon" : "bg-status-error-icon";
  const width = Math.round(num * 100);
  return /* @__PURE__ */ jsxs("div", { className: "flex items-center gap-2", children: [
    /* @__PURE__ */ jsxs("span", { className: `text-sm font-medium ${color}`, children: [
      pct,
      "%"
    ] }),
    /* @__PURE__ */ jsx("div", { className: "w-24 h-2 bg-muted rounded-full overflow-hidden", children: /* @__PURE__ */ jsx("div", { className: `h-full ${bgColor} rounded-full`, style: { width: `${width}%` } }) })
  ] });
}
function OrderPreview({ payload }) {
  const t = useT();
  const lineItems = payload.lineItems || [];
  const customerName = payload.customerName || "";
  const currencyCode = payload.currencyCode || "";
  const notes = payload.notes || "";
  const deliveryDate = payload.requestedDeliveryDate || "";
  return /* @__PURE__ */ jsxs("div", { className: "mt-2 space-y-2 text-xs", children: [
    customerName && /* @__PURE__ */ jsxs("div", { className: "flex gap-1", children: [
      /* @__PURE__ */ jsxs("span", { className: "text-muted-foreground", children: [
        t("inbox_ops.preview.customer", "Customer"),
        ":"
      ] }),
      /* @__PURE__ */ jsx("span", { children: customerName }),
      typeof payload.customerEmail === "string" && /* @__PURE__ */ jsxs("span", { className: "text-muted-foreground", children: [
        "(",
        payload.customerEmail,
        ")"
      ] })
    ] }),
    lineItems.length > 0 && /* @__PURE__ */ jsx("div", { className: "border rounded overflow-hidden", children: /* @__PURE__ */ jsxs("table", { className: "w-full text-xs", children: [
      /* @__PURE__ */ jsx("thead", { children: /* @__PURE__ */ jsxs("tr", { className: "bg-muted/50", children: [
        /* @__PURE__ */ jsx("th", { className: "text-left px-2 py-1 font-medium", children: t("inbox_ops.preview.product", "Product") }),
        /* @__PURE__ */ jsx("th", { className: "text-right px-2 py-1 font-medium", children: t("inbox_ops.preview.qty", "Qty") }),
        /* @__PURE__ */ jsx("th", { className: "text-right px-2 py-1 font-medium", children: t("inbox_ops.preview.price", "Price") })
      ] }) }),
      /* @__PURE__ */ jsx("tbody", { children: lineItems.map((item, index) => /* @__PURE__ */ jsxs("tr", { className: "border-t", children: [
        /* @__PURE__ */ jsx("td", { className: "px-2 py-1", children: item.productName || "\u2014" }),
        /* @__PURE__ */ jsx("td", { className: "px-2 py-1 text-right", children: String(item.quantity ?? "") }),
        /* @__PURE__ */ jsx("td", { className: "px-2 py-1 text-right", children: item.unitPrice ? `${item.unitPrice} ${currencyCode}` : "\u2014" })
      ] }, index)) })
    ] }) }),
    (deliveryDate || notes) && /* @__PURE__ */ jsxs("div", { className: "flex flex-wrap gap-3", children: [
      deliveryDate && /* @__PURE__ */ jsxs("div", { className: "flex gap-1", children: [
        /* @__PURE__ */ jsxs("span", { className: "text-muted-foreground", children: [
          t("inbox_ops.preview.delivery", "Delivery"),
          ":"
        ] }),
        /* @__PURE__ */ jsx("span", { children: deliveryDate })
      ] }),
      notes && /* @__PURE__ */ jsxs("div", { className: "flex gap-1", children: [
        /* @__PURE__ */ jsxs("span", { className: "text-muted-foreground", children: [
          t("inbox_ops.preview.notes", "Notes"),
          ":"
        ] }),
        /* @__PURE__ */ jsx("span", { className: "truncate max-w-[200px]", children: notes })
      ] })
    ] })
  ] });
}
function ProductPreview({ payload }) {
  const t = useT();
  const title = payload.title || "";
  const sku = payload.sku || "";
  const unitPrice = payload.unitPrice || "";
  const currencyCode = payload.currencyCode || "";
  const kind = payload.kind || "product";
  return /* @__PURE__ */ jsxs("div", { className: "mt-2 space-y-1 text-xs", children: [
    title && /* @__PURE__ */ jsxs("div", { className: "flex gap-1", children: [
      /* @__PURE__ */ jsxs("span", { className: "text-muted-foreground", children: [
        t("inbox_ops.preview.product_title", "Title"),
        ":"
      ] }),
      /* @__PURE__ */ jsx("span", { className: "font-medium", children: title })
    ] }),
    /* @__PURE__ */ jsxs("div", { className: "flex flex-wrap gap-3", children: [
      sku && /* @__PURE__ */ jsxs("div", { className: "flex gap-1", children: [
        /* @__PURE__ */ jsxs("span", { className: "text-muted-foreground", children: [
          t("inbox_ops.preview.sku", "SKU"),
          ":"
        ] }),
        /* @__PURE__ */ jsx("span", { children: sku })
      ] }),
      unitPrice && /* @__PURE__ */ jsxs("div", { className: "flex gap-1", children: [
        /* @__PURE__ */ jsxs("span", { className: "text-muted-foreground", children: [
          t("inbox_ops.preview.price", "Price"),
          ":"
        ] }),
        /* @__PURE__ */ jsxs("span", { children: [
          unitPrice,
          currencyCode ? ` ${currencyCode}` : ""
        ] })
      ] }),
      /* @__PURE__ */ jsxs("div", { className: "flex gap-1", children: [
        /* @__PURE__ */ jsxs("span", { className: "text-muted-foreground", children: [
          t("inbox_ops.edit_dialog.kind", "Kind"),
          ":"
        ] }),
        /* @__PURE__ */ jsx("span", { children: kind })
      ] })
    ] })
  ] });
}
function ActionCard({
  action,
  discrepancies,
  actionTypeLabels,
  onAccept,
  onReject,
  onRetry,
  onEdit,
  translatedDescription,
  resolveDiscrepancyDescription
}) {
  const t = useT();
  const Icon = ACTION_TYPE_ICONS[action.actionType] || Package;
  const label = actionTypeLabels[action.actionType] || action.actionType;
  const resolveActionDescription = useActionDescriptionResolver();
  const actionDiscrepancies = discrepancies.filter((d) => d.actionId === action.id && !d.resolved);
  const hasBlockingDiscrepancies = actionDiscrepancies.some((d) => d.severity === "error");
  const displayDescription = translatedDescription || resolveActionDescription(action.description, action.payload);
  if (action.status === "executed") {
    return /* @__PURE__ */ jsxs("div", { className: "border rounded-lg p-3 md:p-4 bg-status-success-bg border-status-success-border", children: [
      /* @__PURE__ */ jsxs("div", { className: "flex items-center gap-2 mb-2", children: [
        /* @__PURE__ */ jsx(CheckCircle, { className: "h-5 w-5 text-status-success-icon flex-shrink-0" }),
        /* @__PURE__ */ jsx("span", { className: "text-sm font-medium", children: label })
      ] }),
      /* @__PURE__ */ jsx("p", { className: "text-sm text-muted-foreground", children: displayDescription }),
      action.createdEntityId && /* @__PURE__ */ jsx("div", { className: "mt-2", children: /* @__PURE__ */ jsxs("span", { className: "text-xs text-status-success-text", children: [
        t("inbox_ops.action.created_entity", "Created {type}").replace("{type}", action.createdEntityType || ""),
        " \xB7 ",
        action.executedAt && new Date(action.executedAt).toLocaleString()
      ] }) })
    ] });
  }
  if (action.status === "rejected") {
    return /* @__PURE__ */ jsxs("div", { className: "border rounded-lg p-3 md:p-4 bg-muted/50 opacity-60", children: [
      /* @__PURE__ */ jsxs("div", { className: "flex items-center gap-2 mb-2", children: [
        /* @__PURE__ */ jsx(XCircle, { className: "h-5 w-5 text-muted-foreground flex-shrink-0" }),
        /* @__PURE__ */ jsx("span", { className: "text-sm font-medium line-through", children: label }),
        /* @__PURE__ */ jsx("span", { className: "text-xs text-muted-foreground", children: t("inbox_ops.status.rejected", "Rejected") })
      ] }),
      /* @__PURE__ */ jsx("p", { className: "text-sm text-muted-foreground", children: displayDescription })
    ] });
  }
  if (action.status === "failed") {
    return /* @__PURE__ */ jsxs("div", { className: "border rounded-lg p-3 md:p-4 bg-status-error-bg border-status-error-border", children: [
      /* @__PURE__ */ jsxs("div", { className: "flex items-center gap-2 mb-2", children: [
        /* @__PURE__ */ jsx(AlertTriangle, { className: "h-5 w-5 text-status-error-icon flex-shrink-0" }),
        /* @__PURE__ */ jsx("span", { className: "text-sm font-medium", children: label }),
        /* @__PURE__ */ jsx("span", { className: "text-xs text-status-error-text", children: t("inbox_ops.extraction_failed", "Failed") })
      ] }),
      /* @__PURE__ */ jsx("p", { className: "text-sm text-muted-foreground", children: displayDescription }),
      action.executionError && /* @__PURE__ */ jsx("p", { className: "text-xs text-status-error-text mt-1", children: action.executionError }),
      /* @__PURE__ */ jsxs("div", { className: "mt-3 flex items-center gap-2", children: [
        /* @__PURE__ */ jsxs(
          Button,
          {
            type: "button",
            size: "sm",
            className: "h-11 md:h-9",
            onClick: () => onRetry(action.id),
            children: [
              /* @__PURE__ */ jsx(RefreshCw, { className: "h-4 w-4 mr-1" }),
              t("inbox_ops.action.retry", "Retry")
            ]
          }
        ),
        /* @__PURE__ */ jsxs(
          Button,
          {
            type: "button",
            variant: "outline",
            size: "sm",
            className: "h-11 md:h-9",
            onClick: () => onEdit(action),
            children: [
              /* @__PURE__ */ jsx(Pencil, { className: "h-4 w-4 mr-1" }),
              t("inbox_ops.action.edit", "Edit")
            ]
          }
        ),
        /* @__PURE__ */ jsxs(
          Button,
          {
            type: "button",
            variant: "outline",
            size: "sm",
            className: "h-11 md:h-9",
            onClick: () => onReject(action.id),
            children: [
              /* @__PURE__ */ jsx(XCircle, { className: "h-4 w-4 mr-1" }),
              t("inbox_ops.action.reject", "Reject")
            ]
          }
        )
      ] })
    ] });
  }
  if (action.status !== "pending") {
    const isProcessing = action.status === "processing";
    const statusLabel = action.status === "accepted" ? t("inbox_ops.status.accepted", "Accepted") : isProcessing ? t("inbox_ops.status.processing", "Processing") : action.status;
    return /* @__PURE__ */ jsxs("div", { className: "border rounded-lg p-3 md:p-4 bg-muted/50", children: [
      /* @__PURE__ */ jsxs("div", { className: "flex items-center gap-2 mb-2", children: [
        isProcessing ? /* @__PURE__ */ jsx(RefreshCw, { className: "h-5 w-5 text-muted-foreground flex-shrink-0 animate-spin" }) : /* @__PURE__ */ jsx(CheckCircle, { className: "h-5 w-5 text-muted-foreground flex-shrink-0" }),
        /* @__PURE__ */ jsx("span", { className: "text-sm font-medium", children: label }),
        /* @__PURE__ */ jsx("span", { className: "text-xs text-muted-foreground", children: statusLabel })
      ] }),
      /* @__PURE__ */ jsx("p", { className: "text-sm text-muted-foreground", children: displayDescription })
    ] });
  }
  const hasNameIssue = hasContactNameIssue(action);
  return /* @__PURE__ */ jsxs("div", { className: "border rounded-lg p-3 md:p-4", children: [
    /* @__PURE__ */ jsxs("div", { className: "flex items-center gap-2 mb-2", children: [
      /* @__PURE__ */ jsx(Icon, { className: "h-5 w-5 text-primary flex-shrink-0" }),
      /* @__PURE__ */ jsx("span", { className: "text-sm font-medium", children: label }),
      /* @__PURE__ */ jsx(ConfidenceBadge, { value: action.confidence })
    ] }),
    /* @__PURE__ */ jsx("p", { className: "text-sm text-foreground/80 mb-2", children: displayDescription }),
    (action.actionType === "create_order" || action.actionType === "create_quote") && /* @__PURE__ */ jsx(OrderPreview, { payload: action.payload }),
    action.actionType === "create_product" && /* @__PURE__ */ jsx(ProductPreview, { payload: action.payload }),
    actionDiscrepancies.length > 0 && /* @__PURE__ */ jsx("div", { className: "mb-3 space-y-1", children: actionDiscrepancies.map((d) => /* @__PURE__ */ jsxs("div", { className: `flex items-start gap-2 text-xs rounded px-2 py-1.5 ${d.severity === "error" ? "bg-status-error-bg text-status-error-text" : "bg-status-warning-bg text-status-warning-text"}`, children: [
      /* @__PURE__ */ jsx(AlertTriangle, { className: "h-3 w-3 mt-0.5 flex-shrink-0" }),
      /* @__PURE__ */ jsxs("div", { children: [
        /* @__PURE__ */ jsx("span", { children: resolveDiscrepancyDescription ? resolveDiscrepancyDescription(d.description, d.foundValue) : d.description }),
        (d.expectedValue || d.foundValue) && /* @__PURE__ */ jsxs("div", { className: "mt-0.5 text-overline opacity-80", children: [
          d.expectedValue && /* @__PURE__ */ jsxs("span", { children: [
            t("inbox_ops.discrepancy.expected", "Expected"),
            ": ",
            d.expectedValue
          ] }),
          d.expectedValue && d.foundValue && /* @__PURE__ */ jsx("span", { children: " \xB7 " }),
          d.foundValue && /* @__PURE__ */ jsxs("span", { children: [
            t("inbox_ops.discrepancy.found", "Found"),
            ": ",
            d.foundValue
          ] })
        ] })
      ] })
    ] }, d.id)) }),
    hasNameIssue && /* @__PURE__ */ jsxs("div", { className: "mb-3 flex items-start gap-2 text-xs rounded px-2 py-1.5 bg-status-warning-bg text-status-warning-text", children: [
      /* @__PURE__ */ jsx(AlertTriangle, { className: "h-3 w-3 mt-0.5 flex-shrink-0" }),
      /* @__PURE__ */ jsx("span", { children: action.actionType === "link_contact" ? t("inbox_ops.contact.link_name_missing_warning", "Contact name is missing. Please edit and provide a name before accepting.") : t("inbox_ops.contact.name_missing_warning", "First and last name could not be extracted. Please edit before accepting.") })
    ] }),
    /* @__PURE__ */ jsxs("div", { className: "flex items-center gap-2", children: [
      /* @__PURE__ */ jsx("div", { title: hasNameIssue ? action.actionType === "link_contact" ? t("inbox_ops.contact.link_name_missing_warning", "Contact name is missing. Please edit and provide a name before accepting.") : t("inbox_ops.contact.name_missing_warning", "First and last name could not be extracted. Please edit before accepting.") : hasBlockingDiscrepancies ? t("inbox_ops.action.accept_blocked", "Resolve errors before accepting") : void 0, children: /* @__PURE__ */ jsxs(
        Button,
        {
          type: "button",
          size: "sm",
          className: "h-11 md:h-9",
          onClick: () => onAccept(action.id),
          disabled: hasBlockingDiscrepancies || hasNameIssue,
          children: [
            /* @__PURE__ */ jsx(CheckCircle, { className: "h-4 w-4 mr-1" }),
            t("inbox_ops.action.accept", "Accept")
          ]
        }
      ) }),
      /* @__PURE__ */ jsxs(
        Button,
        {
          type: "button",
          variant: "outline",
          size: "sm",
          className: "h-11 md:h-9",
          onClick: () => onEdit(action),
          children: [
            /* @__PURE__ */ jsx(Pencil, { className: "h-4 w-4 mr-1" }),
            t("inbox_ops.action.edit", "Edit")
          ]
        }
      ),
      /* @__PURE__ */ jsxs(
        Button,
        {
          type: "button",
          variant: "outline",
          size: "sm",
          className: "h-11 md:h-9",
          onClick: () => onReject(action.id),
          children: [
            /* @__PURE__ */ jsx(XCircle, { className: "h-4 w-4 mr-1" }),
            t("inbox_ops.action.reject", "Reject")
          ]
        }
      )
    ] })
  ] });
}
export {
  ActionCard,
  ConfidenceBadge,
  hasContactNameIssue,
  useActionDescriptionResolver,
  useActionTypeLabels,
  useDiscrepancyDescriptions
};
//# sourceMappingURL=ActionCard.js.map
