"use client";
import { jsx, jsxs } from "react/jsx-runtime";
import * as React from "react";
import { Building2, CalendarClock, Check, ChevronDown, FileText, Save, Trash2, Users, Workflow } from "lucide-react";
import { cn } from "@open-mercato/shared/lib/utils";
import { useT } from "@open-mercato/shared/lib/i18n/context";
import { Button } from "@open-mercato/ui/primitives/button";
import { IconButton } from "@open-mercato/ui/primitives/icon-button";
import { SendObjectMessageDialog } from "@open-mercato/ui/backend/messages";
import { Popover, PopoverContent, PopoverTrigger } from "@open-mercato/ui/primitives/popover";
import { ObjectHistoryButton } from "./ObjectHistoryButton.js";
import { useCustomerDictionary } from "./hooks/useCustomerDictionary.js";
import { formatFallbackLabel } from "./utils.js";
import { isTerminalPipelineOutcomeLabel } from "./pipelineStageUtils.js";
function formatCurrency(amount, currency) {
  if (!amount) return null;
  const parsed = Number(amount);
  if (!Number.isFinite(parsed)) return currency ? `${amount} ${currency}` : amount;
  if (!currency) return parsed.toLocaleString();
  try {
    return new Intl.NumberFormat(void 0, { style: "currency", currency }).format(parsed);
  } catch {
    return `${parsed.toLocaleString()} ${currency}`;
  }
}
function formatDate(value) {
  if (!value) return null;
  const date = new Date(value);
  if (Number.isNaN(date.getTime())) return null;
  return date.toLocaleDateString(void 0, { month: "short", day: "numeric", year: "numeric" });
}
const headerChipDotVariantClasses = {
  info: "bg-status-info-icon",
  warning: "bg-status-warning-icon",
  success: "bg-status-success-icon",
  error: "bg-status-error-icon",
  neutral: "bg-status-neutral-icon"
};
const HEADER_ICON_BUTTON_CLASS = "size-8 rounded-md";
function HeaderChip({
  children,
  icon,
  variant
}) {
  return /* @__PURE__ */ jsxs("span", { className: "inline-flex items-center gap-1.5 rounded-sm bg-muted px-2 py-1 text-xs font-medium leading-none text-muted-foreground", children: [
    variant ? /* @__PURE__ */ jsx("span", { className: cn("size-2 rounded-full", headerChipDotVariantClasses[variant]) }) : null,
    icon ? /* @__PURE__ */ jsx("span", { className: "text-muted-foreground", children: icon }) : null,
    children
  ] });
}
function StageActionButton({
  stageOptions,
  currentStageId,
  onStageChange,
  disabled,
  isSaving
}) {
  const t = useT();
  const [open, setOpen] = React.useState(false);
  const sortedStages = React.useMemo(
    () => [...stageOptions].filter((stage) => !isTerminalPipelineOutcomeLabel(stage.label)).sort((left, right) => left.order - right.order),
    [stageOptions]
  );
  const currentStage = React.useMemo(
    () => sortedStages.find((stage) => stage.id === currentStageId) ?? null,
    [currentStageId, sortedStages]
  );
  if (!sortedStages.length) return null;
  return /* @__PURE__ */ jsxs(Popover, { open, onOpenChange: setOpen, children: [
    /* @__PURE__ */ jsx(PopoverTrigger, { asChild: true, children: /* @__PURE__ */ jsxs(
      Button,
      {
        type: "button",
        variant: "outline",
        size: "sm",
        disabled: disabled || isSaving,
        className: "h-8 max-w-[13rem] rounded-md px-3",
        children: [
          /* @__PURE__ */ jsx(Workflow, { className: "size-4" }),
          /* @__PURE__ */ jsx("span", { className: "truncate", children: currentStage?.label ?? t("customers.deals.detail.actions.moveStage", "Move stage") }),
          /* @__PURE__ */ jsx(ChevronDown, { className: "size-4" })
        ]
      }
    ) }),
    /* @__PURE__ */ jsxs(PopoverContent, { align: "end", className: "w-64 p-1", children: [
      /* @__PURE__ */ jsxs("div", { className: "border-b border-border px-3 py-2", children: [
        /* @__PURE__ */ jsx("div", { className: "text-xs font-semibold text-foreground", children: t("customers.deals.detail.stageMenu.title", "Update pipeline stage") }),
        /* @__PURE__ */ jsx("div", { className: "mt-0.5 text-xs text-muted-foreground", children: t("customers.deals.detail.stageMenu.description", "Move the deal forward without opening the form.") })
      ] }),
      /* @__PURE__ */ jsx("div", { className: "py-1", children: sortedStages.map((stage) => {
        const isCurrent = stage.id === currentStageId;
        return /* @__PURE__ */ jsxs(
          Button,
          {
            type: "button",
            variant: "ghost",
            size: "sm",
            disabled: disabled || isSaving || isCurrent,
            className: "h-auto w-full justify-between rounded-md px-3 py-2 text-left",
            onClick: () => {
              setOpen(false);
              if (!isCurrent) {
                void onStageChange(stage.id);
              }
            },
            children: [
              /* @__PURE__ */ jsx("span", { className: "min-w-0 truncate text-sm font-medium", children: stage.label }),
              isCurrent ? /* @__PURE__ */ jsx(Check, { className: "size-4 text-foreground" }) : null
            ]
          },
          stage.id
        );
      }) })
    ] })
  ] });
}
function DealDetailHeader({
  deal,
  owner,
  people,
  companies,
  pipelineName,
  stageOptions = [],
  currentStageId = null,
  onStageChange,
  isStageSaving = false,
  onSave,
  onDelete,
  isDirty,
  isSaving
}) {
  const t = useT();
  const amountLabel = React.useMemo(
    () => formatCurrency(deal.valueAmount, deal.valueCurrency),
    [deal.valueAmount, deal.valueCurrency]
  );
  const createdAtLabel = React.useMemo(() => formatDate(deal.createdAt), [deal.createdAt]);
  const expectedCloseLabel = React.useMemo(() => formatDate(deal.expectedCloseAt), [deal.expectedCloseAt]);
  const { data: statusDictionary } = useCustomerDictionary("deal-statuses", 0, deal.organizationId ?? null);
  const statusEntry = deal.status ? statusDictionary?.map?.[deal.status] : null;
  const companyLabel = React.useMemo(() => {
    const primaryCompany = companies[0];
    if (!primaryCompany) return null;
    const extraCount = companies.length - 1;
    return extraCount > 0 ? `${primaryCompany.label} +${extraCount}` : primaryCompany.label;
  }, [companies]);
  const timelineLabel = React.useMemo(() => {
    if (createdAtLabel && expectedCloseLabel) {
      return t("customers.deals.detail.header.timeline", "Created {{created}} \xB7 Expected close {{expected}}", {
        created: createdAtLabel,
        expected: expectedCloseLabel
      });
    }
    if (createdAtLabel) {
      return t("customers.deals.detail.header.createdAt", "Created {{date}}", { date: createdAtLabel });
    }
    if (expectedCloseLabel) {
      return t("customers.deals.detail.header.expectedClose", "Expected close {{date}}", { date: expectedCloseLabel });
    }
    return null;
  }, [createdAtLabel, expectedCloseLabel, t]);
  const statusLabel = statusEntry?.label ?? (deal.status ? formatFallbackLabel(deal.status) : null);
  const showStatusChip = statusLabel && (!deal.closureOutcome || !isTerminalPipelineOutcomeLabel(deal.status));
  const pipelineBadgeLabel = pipelineName ?? null;
  const canMoveStage = stageOptions.length > 0 && !deal.closureOutcome && typeof onStageChange === "function";
  const messageSubtitle = React.useMemo(() => [companyLabel, amountLabel].filter(Boolean).join(" \xB7 ") || statusLabel || void 0, [amountLabel, companyLabel, statusLabel]);
  return /* @__PURE__ */ jsxs("div", { className: "flex flex-col gap-5 xl:flex-row xl:items-start xl:justify-between", children: [
    /* @__PURE__ */ jsxs("div", { className: "flex min-w-0 gap-5", children: [
      /* @__PURE__ */ jsx("div", { className: "flex size-16 shrink-0 items-center justify-center rounded-lg border border-border bg-muted text-muted-foreground", children: /* @__PURE__ */ jsx(FileText, { className: "size-7" }) }),
      /* @__PURE__ */ jsxs("div", { className: "min-w-0 space-y-3", children: [
        /* @__PURE__ */ jsxs("div", { className: "flex flex-wrap items-baseline gap-2", children: [
          /* @__PURE__ */ jsx("h1", { className: "min-w-0 truncate text-2xl font-bold leading-tight text-foreground md:text-2xl", children: deal.title || t("customers.deals.detail.untitled", "Untitled deal") }),
          /* @__PURE__ */ jsx("span", { className: "rounded-sm bg-muted px-2 py-1 text-overline font-semibold uppercase tracking-[0.04em] text-muted-foreground", children: t("customers.deals.detail.badge.deal", "Deal") })
        ] }),
        /* @__PURE__ */ jsxs("div", { className: "flex flex-wrap items-center gap-x-4 gap-y-2 text-sm text-muted-foreground", children: [
          companyLabel ? /* @__PURE__ */ jsxs("span", { className: "inline-flex items-center gap-1.5", children: [
            /* @__PURE__ */ jsx(Building2, { className: "size-3.5" }),
            companyLabel
          ] }) : null,
          timelineLabel ? /* @__PURE__ */ jsxs("span", { className: "inline-flex items-center gap-1.5", children: [
            /* @__PURE__ */ jsx(CalendarClock, { className: "size-3.5" }),
            timelineLabel
          ] }) : null,
          amountLabel ? /* @__PURE__ */ jsx("span", { className: "font-semibold text-foreground", children: amountLabel }) : null
        ] }),
        /* @__PURE__ */ jsxs("div", { className: "flex flex-wrap items-center gap-2", children: [
          showStatusChip ? /* @__PURE__ */ jsx(HeaderChip, { variant: "info", children: statusLabel }) : null,
          deal.pipelineStage && !isTerminalPipelineOutcomeLabel(deal.pipelineStage) ? /* @__PURE__ */ jsx(HeaderChip, { variant: "warning", children: deal.pipelineStage }) : null,
          pipelineBadgeLabel ? /* @__PURE__ */ jsx(HeaderChip, { icon: /* @__PURE__ */ jsx(Workflow, { className: "size-3.5" }), children: pipelineBadgeLabel }) : null,
          deal.closureOutcome ? /* @__PURE__ */ jsx(HeaderChip, { variant: deal.closureOutcome === "won" ? "success" : "error", children: deal.closureOutcome === "won" ? t("customers.deals.detail.badge.won", "Won") : t("customers.deals.detail.badge.lost", "Lost") }) : null,
          !companyLabel && people.length > 0 ? /* @__PURE__ */ jsx(HeaderChip, { icon: /* @__PURE__ */ jsx(Users, { className: "size-3.5" }), children: people[0]?.label }) : null,
          owner && !pipelineBadgeLabel ? /* @__PURE__ */ jsx(HeaderChip, { icon: /* @__PURE__ */ jsx(Workflow, { className: "size-3.5" }), children: owner.name }) : null
        ] })
      ] })
    ] }),
    /* @__PURE__ */ jsxs("div", { className: "flex items-center gap-2 xl:justify-end", children: [
      canMoveStage ? /* @__PURE__ */ jsx(
        StageActionButton,
        {
          stageOptions,
          currentStageId,
          onStageChange,
          disabled: isDirty || isSaving,
          isSaving: isStageSaving
        }
      ) : null,
      /* @__PURE__ */ jsx(
        SendObjectMessageDialog,
        {
          object: {
            entityModule: "customers",
            entityType: "deal",
            entityId: deal.id,
            previewData: {
              title: deal.title || t("customers.deals.detail.untitled", "Untitled deal"),
              subtitle: messageSubtitle
            }
          },
          viewHref: `/backend/customers/deals/${deal.id}`,
          buttonVariant: "outline",
          buttonSize: "icon",
          buttonClassName: HEADER_ICON_BUTTON_CLASS,
          buttonLabel: t("customers.deals.detail.actions.sendMessage", "Send message")
        }
      ),
      /* @__PURE__ */ jsx(
        ObjectHistoryButton,
        {
          resourceKind: "customers.deal",
          resourceId: deal.id,
          organizationId: deal.organizationId ?? void 0,
          includeRelated: true
        }
      ),
      /* @__PURE__ */ jsx(
        IconButton,
        {
          variant: "outline",
          size: "sm",
          type: "button",
          "aria-label": t("customers.deals.detail.actions.delete", "Delete"),
          className: "h-8 w-8 rounded-md",
          onClick: () => {
            void onDelete();
          },
          children: /* @__PURE__ */ jsx(Trash2, { className: "size-4" })
        }
      ),
      /* @__PURE__ */ jsxs(
        Button,
        {
          type: "button",
          size: "sm",
          onClick: onSave,
          disabled: !isDirty || isSaving,
          className: "h-8 rounded-md px-3",
          children: [
            /* @__PURE__ */ jsx(Save, { className: "size-4" }),
            t("customers.deals.detail.actions.save", "Save")
          ]
        }
      )
    ] })
  ] });
}
export {
  DealDetailHeader
};
//# sourceMappingURL=DealDetailHeader.js.map
