"use client";
import { jsx, jsxs } from "react/jsx-runtime";
import * as React from "react";
import {
  CrudForm
} from "@open-mercato/ui/backend/CrudForm";
import { Button } from "@open-mercato/ui/primitives/button";
import {
  Select,
  SelectContent,
  SelectItem,
  SelectItemLeading,
  SelectTrigger,
  SelectTriggerLeading,
  SelectValue
} from "@open-mercato/ui/primitives/select";
import {
  renderDictionaryColor,
  renderDictionaryIcon
} from "@open-mercato/core/modules/dictionaries/components/dictionaryAppearance";
import { collectCustomFieldValues } from "@open-mercato/ui/backend/utils/customFieldValues";
import { createCrudFormError } from "@open-mercato/ui/backend/utils/serverErrors";
import { useT } from "@open-mercato/shared/lib/i18n/context";
import { useOrganizationScopeVersion } from "@open-mercato/shared/lib/frontend/useOrganizationScope";
import { CUSTOMER_INTERACTION_ENTITY_ID } from "../../lib/interactionCompatibility.js";
import { normalizeCustomFieldSubmitValue } from "./customFieldUtils.js";
import { useCustomerDictionary } from "./hooks/useCustomerDictionary.js";
function TaskForm({
  mode,
  initialValues,
  onSubmit,
  onCancel,
  submitLabel,
  cancelLabel,
  isSubmitting = false,
  formEntityId = CUSTOMER_INTERACTION_ENTITY_ID,
  useCanonicalInteractions = false
}) {
  const t = useT();
  const containerRef = React.useRef(null);
  const scopeVersion = useOrganizationScopeVersion();
  const statusDictionary = useCustomerDictionary("interaction-statuses", scopeVersion);
  const statusOptions = React.useMemo(() => {
    const entries = statusDictionary.data?.entries ?? [];
    if (entries.length > 0) {
      return entries.map((entry) => ({
        value: entry.value,
        label: entry.label,
        color: entry.color ?? null,
        icon: entry.icon ?? null
      }));
    }
    return [
      { value: "planned", label: t("customers.interactions.status.planned", "Planned") },
      { value: "in_progress", label: t("customers.interactions.status.in_progress", "In progress") },
      { value: "waiting", label: t("customers.interactions.status.waiting", "Waiting / blocked") },
      { value: "done", label: t("customers.interactions.status.done", "Done") },
      { value: "canceled", label: t("customers.interactions.status.canceled", "Canceled") }
    ];
  }, [statusDictionary.data, t]);
  const fields = React.useMemo(
    () => buildTaskFormFields({ useCanonicalInteractions, statusOptions, t }),
    [statusOptions, t, useCanonicalInteractions]
  );
  const groups = React.useMemo(
    () => buildTaskFormGroups({ useCanonicalInteractions, t }),
    [t, useCanonicalInteractions]
  );
  const resolvedSubmitLabel = submitLabel ?? (mode === "edit" ? t("customers.people.detail.tasks.form.submitEdit", "Update task (\u2318/Ctrl + Enter)") : t("customers.people.detail.tasks.form.submitCreate", "Save task (\u2318/Ctrl + Enter)"));
  const resolvedCancelLabel = cancelLabel ?? t("customers.people.detail.tasks.cancel", "Cancel");
  const handleKeyDown = React.useCallback(
    (event) => {
      if ((event.metaKey || event.ctrlKey) && event.key === "Enter") {
        event.preventDefault();
        const form = containerRef.current?.querySelector("form");
        form?.requestSubmit();
      }
      if (event.key === "Escape") {
        event.preventDefault();
        onCancel();
      }
    },
    [onCancel]
  );
  const handleSubmit = React.useCallback(
    async (values) => {
      const payload = buildTaskSubmitPayload(values, t);
      await onSubmit(payload);
    },
    [onSubmit, t]
  );
  const resolvedInitialValues = React.useMemo(() => {
    if (mode !== "create") return initialValues;
    if (useCanonicalInteractions) return { status: "planned", ...initialValues ?? {} };
    return initialValues;
  }, [initialValues, mode, useCanonicalInteractions]);
  return /* @__PURE__ */ jsx("div", { ref: containerRef, onKeyDown: handleKeyDown, children: /* @__PURE__ */ jsx(
    CrudForm,
    {
      embedded: true,
      entityId: formEntityId,
      fields,
      groups,
      initialValues: resolvedInitialValues,
      submitLabel: resolvedSubmitLabel,
      onSubmit: handleSubmit,
      extraActions: /* @__PURE__ */ jsx(Button, { type: "button", variant: "outline", onClick: onCancel, disabled: isSubmitting, children: resolvedCancelLabel })
    }
  ) });
}
function TaskStatusSelect({ id, value, setValue, disabled, options, placeholder }) {
  const stringValue = typeof value === "string" ? value : "";
  const activeOption = options.find((option) => option.value === stringValue) ?? null;
  return /* @__PURE__ */ jsxs(
    Select,
    {
      value: stringValue,
      onValueChange: (next) => setValue(next || void 0),
      disabled,
      children: [
        /* @__PURE__ */ jsxs(SelectTrigger, { id, "data-crud-focus-target": "", children: [
          activeOption && (activeOption.icon || activeOption.color) ? /* @__PURE__ */ jsxs(SelectTriggerLeading, { children: [
            renderDictionaryIcon(activeOption.icon, "h-4 w-4"),
            renderDictionaryColor(activeOption.color, "h-3.5 w-3.5 rounded-full")
          ] }) : null,
          /* @__PURE__ */ jsx(SelectValue, { placeholder, children: activeOption?.label })
        ] }),
        /* @__PURE__ */ jsx(SelectContent, { children: options.map((option) => /* @__PURE__ */ jsxs(SelectItem, { value: option.value, children: [
          option.icon || option.color ? /* @__PURE__ */ jsxs(SelectItemLeading, { children: [
            renderDictionaryIcon(option.icon, "h-4 w-4"),
            renderDictionaryColor(option.color, "h-3.5 w-3.5 rounded-full")
          ] }) : null,
          option.label
        ] }, option.value)) })
      ]
    }
  );
}
function buildTaskFormFields(options) {
  const { useCanonicalInteractions, statusOptions, t } = options;
  const statusField = useCanonicalInteractions ? {
    id: "status",
    label: t("customers.people.detail.tasks.fields.status", "Status"),
    type: "custom",
    component: (props) => /* @__PURE__ */ jsx(
      TaskStatusSelect,
      {
        ...props,
        options: statusOptions,
        placeholder: t("customers.people.detail.tasks.fields.statusPlaceholder", "Select a status")
      }
    )
  } : {
    id: "is_done",
    label: t("customers.people.detail.tasks.fields.done", "Mark as done"),
    type: "checkbox"
  };
  return [
    {
      id: "title",
      label: t("customers.people.detail.tasks.fields.title", "Title"),
      type: "text",
      required: true,
      placeholder: t("customers.people.detail.tasks.fields.titlePlaceholder", "Task title")
    },
    {
      id: "scheduledAt",
      label: t("customers.people.detail.tasks.fields.scheduledAt", "Scheduled for"),
      type: "datetime",
      placeholder: t("customers.people.detail.tasks.fields.scheduledAtPlaceholder", "Choose a date and time")
    },
    {
      id: "priority",
      label: t("customers.people.detail.tasks.fields.priority", "Priority"),
      type: "number",
      placeholder: t("customers.people.detail.tasks.fields.priorityPlaceholder", "0-100")
    },
    {
      id: "description",
      label: t("customers.people.detail.tasks.fields.description", "Description"),
      type: "textarea",
      placeholder: t("customers.people.detail.tasks.fields.descriptionPlaceholder", "Add context, outcome, or follow-up notes"),
      layout: "full"
    },
    statusField
  ];
}
function buildTaskFormGroups(options) {
  const { useCanonicalInteractions, t } = options;
  return [
    {
      id: "details",
      title: t("customers.people.detail.tasks.form.details", "Task details"),
      column: 1,
      fields: ["title", "scheduledAt", "description"]
    },
    {
      id: "status",
      title: t("customers.people.detail.tasks.form.status", "Status"),
      column: 2,
      fields: ["priority", useCanonicalInteractions ? "status" : "is_done"]
    },
    {
      id: "attributes",
      title: t("customers.people.detail.tasks.form.customFields", "Task attributes"),
      column: 1,
      kind: "customFields"
    },
    {
      id: "tips",
      title: t("customers.people.detail.tasks.form.tips", "Tips"),
      column: 2,
      component: () => /* @__PURE__ */ jsx("div", { className: "text-sm text-muted-foreground", children: t(
        "customers.people.detail.tasks.form.tipsBody",
        'Tasks save independently from the main customer form. Use clear titles like "Follow up call" or "Send pricing deck".'
      ) })
    }
  ];
}
function buildTaskSubmitPayload(values, t) {
  const rawTitle = typeof values.title === "string" ? values.title.trim() : "";
  if (!rawTitle.length) {
    const message = t("customers.people.detail.tasks.titleRequired", "Task name is required.");
    throw createCrudFormError(message, { title: message });
  }
  const rawPriority = typeof values.priority === "number" || typeof values.priority === "string" ? values.priority : null;
  let priority = null;
  if (rawPriority !== null && rawPriority !== "") {
    const parsed = typeof rawPriority === "number" ? rawPriority : Number(String(rawPriority).trim());
    if (!Number.isInteger(parsed) || parsed < 0 || parsed > 100) {
      const message = t("customers.people.detail.tasks.priorityInvalid", "Enter a whole-number priority between 0 and 100.");
      throw createCrudFormError(message, { priority: message });
    }
    priority = parsed;
  }
  const rawDescription = typeof values.description === "string" ? values.description.trim() : "";
  const rawScheduledAt = typeof values.scheduledAt === "string" ? values.scheduledAt.trim() : "";
  const rawStatus = typeof values.status === "string" ? values.status.trim() : "";
  const status = rawStatus.length ? rawStatus : void 0;
  const base = { title: rawTitle };
  if (status !== void 0) {
    base.status = status;
    base.is_done = status === "done";
  } else if (typeof values.is_done === "boolean") {
    base.is_done = values.is_done;
  }
  base.description = rawDescription || null;
  base.priority = priority;
  base.scheduledAt = rawScheduledAt || null;
  const custom = collectCustomFieldValues(values, {
    transform: (value) => normalizeCustomFieldSubmitValue(value)
  });
  return { base, custom };
}
export {
  TaskForm,
  buildTaskFormFields,
  buildTaskFormGroups,
  buildTaskSubmitPayload
};
//# sourceMappingURL=TaskForm.js.map
