"use client";
import { jsx, jsxs } from "react/jsx-runtime";
import * as React from "react";
import { Mail, Phone, StickyNote } from "lucide-react";
import { z } from "zod";
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogHeader,
  DialogTitle
} from "@open-mercato/ui/primitives/dialog";
import { CrudForm } from "@open-mercato/ui/backend/CrudForm";
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 ACTIVITY_CONTEXT_ID = "customers-deals-kanban:activity-composer";
const TYPE_META = {
  call: {
    titleKey: "customers.deals.kanban.activityComposer.call",
    titleFallback: "Log a call",
    interactionType: "call",
    icon: Phone
  },
  email: {
    titleKey: "customers.deals.kanban.activityComposer.email",
    titleFallback: "Send email",
    interactionType: "email",
    icon: Mail
  },
  note: {
    titleKey: "customers.deals.kanban.activityComposer.note",
    titleFallback: "Add a note",
    interactionType: "note",
    icon: StickyNote
  }
};
function ActivityComposerDialog({
  open,
  context,
  onClose,
  onCreated
}) {
  const t = useT();
  const [formInstanceKey, setFormInstanceKey] = React.useState(0);
  React.useEffect(() => {
    if (open) setFormInstanceKey((current) => current + 1);
  }, [open]);
  const { runMutation, retryLastMutation } = useGuardedMutation({
    contextId: ACTIVITY_CONTEXT_ID,
    blockedMessage: translateWithFallback(t, "ui.forms.flash.saveBlocked", "Save blocked by validation")
  });
  const eitherRequiredMessage = React.useMemo(
    () => context?.type === "email" ? translateWithFallback(
      t,
      "customers.deals.kanban.activityComposer.required.email",
      "Add a subject or body before saving."
    ) : translateWithFallback(
      t,
      "customers.deals.kanban.activityComposer.required.titleOrBody",
      "Add a title or body before saving."
    ),
    [context?.type, t]
  );
  const formSchema = React.useMemo(
    () => z.object({
      title: z.string().optional(),
      phoneNumber: z.string().optional(),
      body: z.string().optional()
    }).refine(
      (values) => values.title?.trim().length || values.body?.trim().length ? true : false,
      {
        message: eitherRequiredMessage,
        path: ["title"]
      }
    ),
    [eitherRequiredMessage]
  );
  const initialValues = React.useMemo(
    () => ({ title: "", phoneNumber: "", body: "" }),
    []
  );
  const isCall = context?.type === "call";
  const fields = React.useMemo(() => {
    const list = [
      {
        // CrudForm auto-focuses the first field on mount; explicit `autoFocus` is rejected
        // by CrudBuiltinField's type and would shadow CrudForm's own focus management.
        id: "title",
        label: translateWithFallback(t, "customers.deals.kanban.activityComposer.title", "Subject"),
        type: "text",
        placeholder: translateWithFallback(
          t,
          "customers.deals.kanban.activityComposer.title.placeholder",
          "Short summary (optional)"
        )
      }
    ];
    if (isCall) {
      list.push({
        id: "phoneNumber",
        label: translateWithFallback(t, "customers.deals.kanban.activityComposer.phone", "Phone number"),
        type: "text",
        placeholder: "+48 ..."
      });
    }
    list.push({
      id: "body",
      label: translateWithFallback(t, "customers.deals.kanban.activityComposer.body", "Notes"),
      type: "textarea",
      rows: 4,
      placeholder: translateWithFallback(
        t,
        "customers.deals.kanban.activityComposer.body.placeholder",
        "What happened? Markdown supported."
      )
    });
    return list;
  }, [isCall, t]);
  const handleSubmit = React.useCallback(
    async (values) => {
      if (!context) return;
      const trimmedTitle = (values.title ?? "").trim();
      const trimmedBody = (values.body ?? "").trim();
      if (!trimmedTitle.length && !trimmedBody.length) {
        throw createCrudFormError(eitherRequiredMessage, { title: eitherRequiredMessage });
      }
      const meta2 = TYPE_META[context.type];
      const payload = {
        entityId: context.entityId,
        interactionType: meta2.interactionType,
        dealId: context.dealId,
        status: "planned"
      };
      if (trimmedTitle.length) payload.title = trimmedTitle;
      if (trimmedBody.length) payload.body = trimmedBody;
      if (context.type === "call" && (values.phoneNumber ?? "").trim().length) {
        payload.phoneNumber = values.phoneNumber.trim();
      }
      const operation = () => createCrud("customers/interactions", payload, {
        errorMessage: translateWithFallback(
          t,
          "customers.deals.kanban.activityComposer.error",
          "Failed to save activity."
        )
      });
      await runMutation({
        operation,
        context: {
          formId: ACTIVITY_CONTEXT_ID,
          resourceKind: "customers.interaction",
          resourceId: context.dealId,
          retryLastMutation
        }
      });
      flash(
        translateWithFallback(t, "customers.deals.kanban.activityComposer.success", "Activity saved."),
        "success"
      );
      onCreated();
      onClose();
    },
    [context, eitherRequiredMessage, onClose, onCreated, retryLastMutation, runMutation, t]
  );
  if (!context) return null;
  const meta = TYPE_META[context.type];
  const Icon = meta.icon;
  const dialogTitle = translateWithFallback(t, meta.titleKey, meta.titleFallback);
  return /* @__PURE__ */ jsx(
    Dialog,
    {
      open,
      onOpenChange: (next) => {
        if (!next) onClose();
      },
      children: /* @__PURE__ */ jsxs(DialogContent, { children: [
        /* @__PURE__ */ jsxs(DialogHeader, { children: [
          /* @__PURE__ */ jsxs(DialogTitle, { className: "flex items-center gap-2", children: [
            /* @__PURE__ */ jsx(Icon, { className: "size-4", "aria-hidden": "true" }),
            dialogTitle
          ] }),
          /* @__PURE__ */ jsx(DialogDescription, { children: translateWithFallback(
            t,
            "customers.deals.kanban.activityComposer.context",
            "Deal: {title}",
            { title: context.dealTitle }
          ) })
        ] }),
        /* @__PURE__ */ jsx(
          CrudForm,
          {
            embedded: true,
            fields,
            initialValues,
            schema: formSchema,
            submitLabel: translateWithFallback(
              t,
              "customers.deals.kanban.activityComposer.submit",
              "Save activity"
            ),
            onSubmit: handleSubmit
          },
          `${context.dealId}:${context.type}:${formInstanceKey}`
        )
      ] })
    }
  );
}
var ActivityComposerDialog_default = ActivityComposerDialog;
export {
  ActivityComposerDialog,
  ActivityComposerDialog_default as default
};
//# sourceMappingURL=ActivityComposerDialog.js.map
