"use client";
import { jsx, jsxs } from "react/jsx-runtime";
import * as React from "react";
import { AlertTriangle, Check, ChevronDown } from "lucide-react";
import { useT } from "@open-mercato/shared/lib/i18n/context";
import { loadDictionaryEntriesByKey } from "@open-mercato/core/modules/dictionaries/lib/clientEntries";
import { Alert, AlertDescription, AlertTitle } from "@open-mercato/ui/primitives/alert";
import { Button } from "@open-mercato/ui/primitives/button";
import { Dialog, DialogContent, DialogFooter, DialogHeader, DialogTitle } from "@open-mercato/ui/primitives/dialog";
import { Textarea } from "@open-mercato/ui/primitives/textarea";
import { useDialogKeyHandler } from "@open-mercato/ui/hooks/useDialogKeyHandler";
import { createLogger } from "@open-mercato/shared/lib/logger";
const logger = createLogger("customers");
function ConfirmDealLostDialog({
  open,
  dealTitle,
  dealValue,
  companyName,
  onClose,
  onConfirm
}) {
  const t = useT();
  const [lossReasonId, setLossReasonId] = React.useState("");
  const [lossNotes, setLossNotes] = React.useState("");
  const [lossReasons, setLossReasons] = React.useState([]);
  const [reasonListOpen, setReasonListOpen] = React.useState(false);
  const [error, setError] = React.useState("");
  const [dictionaryLoadFailed, setDictionaryLoadFailed] = React.useState(false);
  const [isLoadingReasons, setIsLoadingReasons] = React.useState(false);
  const [isConfirming, setIsConfirming] = React.useState(false);
  React.useEffect(() => {
    if (!open) return;
    let cancelled = false;
    setIsLoadingReasons(true);
    setDictionaryLoadFailed(false);
    loadDictionaryEntriesByKey("sales.deal_loss_reason").then((items) => {
      if (!cancelled) setLossReasons(items);
    }).catch((loadError) => {
      logger.error("customers.deals.detail.lossReasons failed", { loadError });
      if (!cancelled) {
        setLossReasons([]);
        setDictionaryLoadFailed(true);
      }
    }).finally(() => {
      if (!cancelled) setIsLoadingReasons(false);
    });
    return () => {
      cancelled = true;
    };
  }, [open]);
  React.useEffect(() => {
    if (!open) return;
    setLossReasonId("");
    setLossNotes("");
    setReasonListOpen(false);
    setError("");
    setDictionaryLoadFailed(false);
    setIsConfirming(false);
  }, [open]);
  const selectedLossReason = React.useMemo(
    () => lossReasons.find((reason) => reason.id === lossReasonId) ?? null,
    [lossReasonId, lossReasons]
  );
  const hasLossReasons = lossReasons.length > 0;
  const reasonUnavailable = !isLoadingReasons && !hasLossReasons;
  const unavailableReasonText = dictionaryLoadFailed ? t("customers.deals.detail.lost.reasonLoadError", "Loss reasons could not be loaded.") : t("customers.deals.detail.lost.reasonUnavailable", "No loss reasons are configured.");
  const reasonHelpText = React.useMemo(() => {
    if (selectedLossReason?.description) return selectedLossReason.description;
    if (isLoadingReasons) {
      return t("customers.deals.detail.lost.reasonLoading", "Loading loss reasons...");
    }
    if (reasonUnavailable) {
      return unavailableReasonText;
    }
    return t("customers.deals.detail.lost.reasonHelp", "Choose the closest reason from the dictionary.");
  }, [isLoadingReasons, reasonUnavailable, selectedLossReason?.description, t, unavailableReasonText]);
  const handleConfirm = React.useCallback(async () => {
    if (isLoadingReasons || reasonUnavailable) {
      setError(unavailableReasonText);
      return;
    }
    if (!lossReasonId) {
      setError(t("customers.deals.detail.lost.reasonRequired", "Please select a loss reason"));
      return;
    }
    setIsConfirming(true);
    try {
      await onConfirm({
        lossReasonId,
        lossNotes: lossNotes.trim() || void 0
      });
    } finally {
      setIsConfirming(false);
    }
  }, [isLoadingReasons, lossNotes, lossReasonId, onConfirm, reasonUnavailable, t, unavailableReasonText]);
  const confirmDisabled = isConfirming || isLoadingReasons || reasonUnavailable || !lossReasonId;
  const handleKeyDown = useDialogKeyHandler({
    onConfirm: () => void handleConfirm(),
    disabled: confirmDisabled
  });
  return /* @__PURE__ */ jsx(Dialog, { open, onOpenChange: (nextOpen) => {
    if (!nextOpen) onClose();
  }, children: /* @__PURE__ */ jsx(DialogContent, { className: "overflow-hidden p-0 sm:max-w-[560px]", onKeyDown: handleKeyDown, children: /* @__PURE__ */ jsxs("div", { className: "overflow-hidden rounded-lg bg-card", children: [
    /* @__PURE__ */ jsx(DialogHeader, { className: "border-b border-border/70 px-7 py-5", children: /* @__PURE__ */ jsxs("div", { className: "flex items-start gap-4", children: [
      /* @__PURE__ */ jsx("div", { className: "flex size-10 shrink-0 items-center justify-center rounded-md bg-destructive/10 text-destructive", children: /* @__PURE__ */ jsx(AlertTriangle, { className: "size-5" }) }),
      /* @__PURE__ */ jsxs("div", { className: "min-w-0", children: [
        /* @__PURE__ */ jsx(DialogTitle, { className: "text-lg font-bold leading-none tracking-tight text-foreground", children: t("customers.deals.detail.lost.title", "Mark deal as Lost?") }),
        /* @__PURE__ */ jsxs("p", { className: "mt-1 text-xs text-muted-foreground", children: [
          dealTitle,
          dealValue ? ` \xB7 ${dealValue}` : "",
          companyName ? ` \xB7 ${companyName}` : ""
        ] })
      ] })
    ] }) }),
    /* @__PURE__ */ jsxs("div", { className: "space-y-6 px-7 py-6", children: [
      /* @__PURE__ */ jsxs(Alert, { variant: "warning", className: "rounded-md", children: [
        /* @__PURE__ */ jsx(AlertTitle, { children: t("customers.deals.detail.lost.warningTitle", "This action closes the deal") }),
        /* @__PURE__ */ jsx(AlertDescription, { children: t("customers.deals.detail.lost.warning", "This action sets the stage to 'Lost' and cannot be undone without 'sales.reopen' permission") })
      ] }),
      /* @__PURE__ */ jsxs("div", { className: "space-y-2", children: [
        /* @__PURE__ */ jsxs("label", { className: "text-sm font-semibold text-foreground", children: [
          t("customers.deals.detail.lost.reasonLabel", "Loss reason"),
          /* @__PURE__ */ jsx("span", { className: "ml-1 text-destructive", children: "*" })
        ] }),
        /* @__PURE__ */ jsxs("div", { className: "space-y-3", children: [
          /* @__PURE__ */ jsxs(
            Button,
            {
              type: "button",
              variant: "outline",
              onClick: () => setReasonListOpen((current) => !current),
              className: "h-auto flex w-full items-center justify-between rounded-md border-2 border-foreground bg-background px-4 py-3 text-left",
              children: [
                /* @__PURE__ */ jsxs("div", { className: "min-w-0", children: [
                  /* @__PURE__ */ jsx("div", { className: "truncate text-base font-semibold text-foreground", children: selectedLossReason?.label ?? (isLoadingReasons ? t("customers.deals.detail.lost.reasonLoadingShort", "Loading...") : t("customers.deals.detail.lost.reasonPlaceholder", "Select loss reason")) }),
                  /* @__PURE__ */ jsx("div", { className: "truncate text-sm text-muted-foreground", children: reasonHelpText })
                ] }),
                /* @__PURE__ */ jsx(ChevronDown, { className: "ml-3 size-4 shrink-0 text-muted-foreground" })
              ]
            }
          ),
          reasonListOpen ? /* @__PURE__ */ jsx("div", { className: "overflow-hidden rounded-md border border-border/80 bg-background", children: hasLossReasons ? lossReasons.map((reason, index) => {
            const isSelected = reason.id === lossReasonId;
            return /* @__PURE__ */ jsxs(
              Button,
              {
                type: "button",
                variant: "ghost",
                onClick: () => {
                  setLossReasonId(reason.id);
                  setReasonListOpen(false);
                  setError("");
                },
                className: `h-auto flex w-full items-center justify-between rounded-none px-4 py-3 text-left ${index < lossReasons.length - 1 ? "border-b border-border/60" : ""} ${isSelected ? "bg-muted/60" : "hover:bg-accent/50"}`,
                children: [
                  /* @__PURE__ */ jsxs("div", { className: "min-w-0", children: [
                    /* @__PURE__ */ jsx("div", { className: "text-base font-semibold text-foreground", children: reason.label }),
                    /* @__PURE__ */ jsx("div", { className: "text-sm text-muted-foreground", children: reason.description ?? t("customers.deals.detail.lost.reasonFallbackDescription", "No description available.") })
                  ] }),
                  isSelected ? /* @__PURE__ */ jsx("span", { className: "ml-3 flex size-6 shrink-0 items-center justify-center rounded-full bg-foreground text-background", children: /* @__PURE__ */ jsx(Check, { className: "size-3.5" }) }) : null
                ]
              },
              reason.id
            );
          }) : /* @__PURE__ */ jsx("div", { className: "px-4 py-3 text-sm text-muted-foreground", children: unavailableReasonText }) }) : null
        ] }),
        reasonUnavailable ? /* @__PURE__ */ jsx("p", { className: "text-xs text-destructive", children: unavailableReasonText }) : null,
        error ? /* @__PURE__ */ jsx("p", { className: "text-xs text-destructive", children: error }) : null
      ] }),
      /* @__PURE__ */ jsxs("div", { className: "space-y-2", children: [
        /* @__PURE__ */ jsx("label", { className: "text-sm font-semibold text-foreground", children: t("customers.deals.detail.lost.notesLabel", "Loss notes (optional)") }),
        /* @__PURE__ */ jsx(
          Textarea,
          {
            value: lossNotes,
            onChange: (event) => setLossNotes(event.target.value),
            placeholder: t("customers.deals.detail.lost.notesPlaceholder", "Additional context about the loss..."),
            rows: 4,
            className: "min-h-[88px] rounded-md border-border/80 px-4 py-3 shadow-none"
          }
        )
      ] })
    ] }),
    /* @__PURE__ */ jsxs(DialogFooter, { className: "border-t border-border/70 px-7 py-4 sm:justify-end", children: [
      /* @__PURE__ */ jsx(Button, { type: "button", variant: "outline", onClick: onClose, children: t("customers.deals.detail.lost.cancel", "Cancel") }),
      /* @__PURE__ */ jsx(
        Button,
        {
          type: "button",
          variant: "destructive",
          disabled: confirmDisabled,
          onClick: () => {
            void handleConfirm();
          },
          children: t("customers.deals.detail.lost.confirm", "Mark as Lost")
        }
      )
    ] })
  ] }) }) });
}
export {
  ConfirmDealLostDialog
};
//# sourceMappingURL=ConfirmDealLostDialog.js.map
