"use client";
import { jsx, jsxs } from "react/jsx-runtime";
import * as React from "react";
import { z } from "zod";
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogHeader,
  DialogTitle
} from "@open-mercato/ui/primitives/dialog";
import { Avatar } from "@open-mercato/ui/primitives/avatar";
import { CrudForm } from "@open-mercato/ui/backend/CrudForm";
import { ComboboxInput } from "@open-mercato/ui/backend/inputs/ComboboxInput";
import { createCrud } from "@open-mercato/ui/backend/utils/crud";
import { createCrudFormError } from "@open-mercato/ui/backend/utils/serverErrors";
import { useGuardedMutation } from "@open-mercato/ui/backend/injection/useGuardedMutation";
import { flash } from "@open-mercato/ui/backend/FlashMessages";
import { useT } from "@open-mercato/shared/lib/i18n/context";
import { translateWithFallback } from "@open-mercato/shared/lib/i18n/translate";
const STATUS_OPTIONS = ["open", "in_progress", "win", "loose"];
const FALLBACK_CURRENCIES = [
  { code: "USD", isBase: true },
  { code: "EUR" },
  { code: "GBP" },
  { code: "PLN" }
];
const QUICK_DEAL_CONTEXT_ID = "customers-deals-kanban:quick-deal";
function QuickDealDialog({
  open,
  context,
  onClose,
  onCreated,
  currentUserId,
  currentUserLabel,
  companies = [],
  currencies
}) {
  const t = useT();
  const [formInstanceKey, setFormInstanceKey] = React.useState(0);
  React.useEffect(() => {
    if (open) setFormInstanceKey((current) => current + 1);
  }, [open]);
  const { runMutation, retryLastMutation } = useGuardedMutation({
    contextId: QUICK_DEAL_CONTEXT_ID,
    blockedMessage: translateWithFallback(t, "ui.forms.flash.saveBlocked", "Save blocked by validation")
  });
  const titleRequiredMessage = translateWithFallback(
    t,
    "customers.deals.kanban.quickDeal.title.required",
    "Title is required."
  );
  const resolvedCurrencies = React.useMemo(
    () => currencies && currencies.length > 0 ? currencies : FALLBACK_CURRENCIES,
    [currencies]
  );
  const defaultCurrencyCode = React.useMemo(() => {
    const base = resolvedCurrencies.find((currency) => currency.isBase);
    return base?.code ?? resolvedCurrencies[0]?.code ?? "USD";
  }, [resolvedCurrencies]);
  const formSchema = React.useMemo(
    () => z.object({
      title: z.string().trim().min(1, titleRequiredMessage),
      valueAmount: z.number().min(0).nullable().optional(),
      // The set of valid currencies is tenant-defined and resolved at runtime; we accept
      // any non-empty string here and let the server (which knows the canonical list)
      // reject anything bogus.
      valueCurrency: z.string().min(1),
      companyId: z.string().optional(),
      status: z.enum(STATUS_OPTIONS),
      probability: z.number().min(0).max(100).nullable().optional(),
      expectedCloseAt: z.string().optional(),
      description: z.string().optional()
    }),
    // Cast widens to QuickDealFormValues so CrudForm's TValues generic stays exact.
    [titleRequiredMessage]
  );
  const initialValues = React.useMemo(
    () => ({
      title: "",
      valueAmount: null,
      valueCurrency: defaultCurrencyCode,
      companyId: "",
      status: "open",
      probability: 25,
      expectedCloseAt: "",
      description: ""
    }),
    [defaultCurrencyCode]
  );
  const fields = React.useMemo(
    () => {
      const list = [
        {
          // CrudForm auto-focuses the first field of the first group on mount; we don't
          // need (and CrudField doesn't accept) an explicit `autoFocus` prop here.
          id: "title",
          label: translateWithFallback(t, "customers.deals.kanban.quickDeal.title.label", "Deal title"),
          type: "text",
          required: true,
          placeholder: translateWithFallback(
            t,
            "customers.deals.kanban.quickDeal.title.placeholder",
            "e.g. Q3 Expansion \u2014 Lighting Package"
          )
        },
        {
          id: "valueAmount",
          label: translateWithFallback(t, "customers.deals.kanban.quickDeal.value", "Value"),
          type: "number",
          layout: "half",
          placeholder: "0"
        },
        {
          id: "valueCurrency",
          label: translateWithFallback(t, "customers.deals.kanban.quickDeal.currency", "Currency"),
          type: "select",
          layout: "half",
          options: resolvedCurrencies.map((currency) => ({
            value: currency.code,
            label: currency.label && currency.label !== currency.code ? `${currency.code} \u2014 ${currency.label}` : currency.code
          }))
        },
        {
          // Company is a typeahead (ComboboxInput) rather than a plain <select>: tenants
          // with hundreds of companies get an unusable dropdown otherwise. The `seedOptions`
          // carry the most-recent companies the page already loaded; an async loader could
          // be added later to hit the companies search endpoint for full coverage.
          id: "companyId",
          label: translateWithFallback(t, "customers.deals.kanban.quickDeal.company", "Company"),
          type: "custom",
          component: ({ value, setValue }) => /* @__PURE__ */ jsx(
            ComboboxInput,
            {
              value: typeof value === "string" ? value : "",
              onChange: (next) => setValue(next),
              seedOptions: companies.map((company) => ({ value: company.id, label: company.label })),
              placeholder: translateWithFallback(
                t,
                "customers.deals.kanban.quickDeal.companyPh",
                "Pick a company or add new\u2026"
              ),
              allowCustomValues: false
            }
          )
        }
      ];
      if (currentUserLabel) {
        list.push({
          id: "owner",
          label: translateWithFallback(t, "customers.deals.kanban.quickDeal.owner", "Owner"),
          type: "custom",
          readOnly: true,
          component: () => /* @__PURE__ */ jsxs("div", { className: "flex h-9 items-center gap-2 rounded-md border border-input bg-card px-3 text-sm", children: [
            /* @__PURE__ */ jsx(Avatar, { label: currentUserLabel, size: "sm" }),
            /* @__PURE__ */ jsx("span", { children: currentUserLabel })
          ] })
        });
      }
      list.push(
        {
          id: "status",
          label: translateWithFallback(t, "customers.deals.kanban.quickDeal.status", "Status"),
          type: "select",
          // Storage value is preserved (`loose` etc.) — only the displayed label is
          // translated, so we never write a localised string back to the DB.
          options: STATUS_OPTIONS.map((statusValue) => ({
            value: statusValue,
            label: translateWithFallback(
              t,
              `customers.deals.kanban.quickDeal.status.${statusValue}`,
              statusValue
            )
          }))
        },
        {
          id: "probability",
          label: translateWithFallback(t, "customers.deals.kanban.quickDeal.probability", "Probability"),
          type: "number",
          layout: "half",
          placeholder: "25"
        },
        {
          id: "expectedCloseAt",
          label: translateWithFallback(t, "customers.deals.kanban.quickDeal.expectedClose", "Expected close"),
          type: "date",
          layout: "half"
        },
        {
          id: "description",
          label: translateWithFallback(t, "customers.deals.kanban.quickDeal.description", "Description"),
          type: "textarea",
          rows: 3,
          placeholder: translateWithFallback(
            t,
            "customers.deals.kanban.quickDeal.description.placeholder",
            "Short context, decision makers or next steps. Markdown supported."
          )
        }
      );
      return list;
    },
    [companies, currentUserLabel, resolvedCurrencies, t]
  );
  const groups = React.useMemo(
    () => [
      {
        id: "basic",
        // No title — keep the basic section flush with the dialog header.
        fields: ["title", "valueAmount", "valueCurrency", "companyId", ...currentUserLabel ? ["owner"] : []]
      },
      {
        id: "more",
        title: translateWithFallback(
          t,
          "customers.deals.kanban.quickDeal.more",
          "More details (probability, close date, description)"
        ),
        fields: ["status", "probability", "expectedCloseAt", "description"]
      }
    ],
    [currentUserLabel, t]
  );
  const handleSubmit = React.useCallback(
    async (values) => {
      if (!context) return;
      const trimmedTitle = values.title.trim();
      if (!trimmedTitle.length) {
        throw createCrudFormError(titleRequiredMessage, { title: titleRequiredMessage });
      }
      const payload = {
        title: trimmedTitle,
        pipelineId: context.pipelineId,
        pipelineStageId: context.pipelineStageId,
        valueCurrency: values.valueCurrency
      };
      if (typeof values.valueAmount === "number" && Number.isFinite(values.valueAmount)) {
        payload.valueAmount = values.valueAmount;
      }
      if (currentUserId) payload.ownerUserId = currentUserId;
      if (values.companyId) payload.companyIds = [values.companyId];
      if (values.status) payload.status = values.status;
      if (typeof values.probability === "number" && Number.isFinite(values.probability)) {
        payload.probability = values.probability;
      }
      if (values.expectedCloseAt && values.expectedCloseAt.trim().length) {
        payload.expectedCloseAt = values.expectedCloseAt;
      }
      if (values.description && values.description.trim().length) {
        payload.description = values.description;
      }
      const operation = () => createCrud("customers/deals", payload, {
        errorMessage: translateWithFallback(t, "customers.deals.create.error", "Failed to create deal.")
      });
      await runMutation({
        operation,
        context: {
          formId: QUICK_DEAL_CONTEXT_ID,
          resourceKind: "customers.deal",
          retryLastMutation
        }
      });
      flash(
        translateWithFallback(
          t,
          "customers.deals.kanban.quickDeal.success",
          "Deal added to {stage}.",
          { stage: context.pipelineStageLabel }
        ),
        "success"
      );
      onCreated();
      onClose();
    },
    [context, currentUserId, onClose, onCreated, retryLastMutation, runMutation, t, titleRequiredMessage]
  );
  if (!context) return null;
  return /* @__PURE__ */ jsx(
    Dialog,
    {
      open,
      onOpenChange: (next) => {
        if (!next) onClose();
      },
      children: /* @__PURE__ */ jsxs(DialogContent, { children: [
        /* @__PURE__ */ jsxs(DialogHeader, { children: [
          /* @__PURE__ */ jsx(DialogTitle, { children: translateWithFallback(t, "customers.deals.kanban.quickDeal.title", "Quick deal") }),
          /* @__PURE__ */ jsx(DialogDescription, { children: translateWithFallback(
            t,
            "customers.deals.kanban.quickDeal.context",
            "Pipeline: {pipeline} \xB7 Stage: {stage}",
            { pipeline: context.pipelineName, stage: context.pipelineStageLabel }
          ) })
        ] }),
        /* @__PURE__ */ jsx(
          CrudForm,
          {
            embedded: true,
            fields,
            groups,
            collapsibleGroups: { pageType: "customers.deals.kanban.quickDeal" },
            initialValues,
            schema: formSchema,
            submitLabel: translateWithFallback(t, "customers.deals.kanban.quickDeal.submit", "Add deal"),
            onSubmit: handleSubmit
          },
          `${context.pipelineStageId}:${formInstanceKey}`
        )
      ] })
    }
  );
}
var QuickDealDialog_default = QuickDealDialog;
export {
  QuickDealDialog,
  QuickDealDialog_default as default
};
//# sourceMappingURL=QuickDealDialog.js.map
