"use client";
import { jsx, jsxs } from "react/jsx-runtime";
import * as React from "react";
import { z } from "zod";
import { useT } from "@open-mercato/shared/lib/i18n/context";
import { CrudForm } from "@open-mercato/ui/backend/CrudForm";
import { Button } from "@open-mercato/ui/primitives/button";
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue
} from "@open-mercato/ui/primitives/select";
import { collectCustomFieldValues } from "@open-mercato/ui/backend/utils/customFieldValues";
import { createCrudFormError } from "@open-mercato/ui/backend/utils/serverErrors";
import { DictionaryEntrySelect } from "@open-mercato/core/modules/dictionaries/components/DictionaryEntrySelect";
import { E } from "../../../../generated/entities.ids.generated.js";
import { toLocalDateTimeInput } from "./utils.js";
import { normalizeCustomFieldSubmitValue } from "./customFieldUtils.js";
const schema = z.object({
  activityType: z.string().min(1),
  subject: z.string().transform((value) => value.trim()).optional(),
  body: z.string().transform((value) => value.trim()).optional(),
  occurredAt: z.string().transform((value) => value.trim()).refine((value) => {
    if (!value) return true;
    const parsed = new Date(value);
    return !Number.isNaN(parsed.getTime());
  }, { message: "customers.people.detail.activities.invalidDate" }).optional()
}).passthrough();
const ACTIVITY_ENTITY_IDS = [E.customers.customer_activity];
function ActivityForm({
  mode,
  initialValues,
  onSubmit,
  onCancel,
  submitLabel,
  cancelLabel,
  isSubmitting = false,
  activityTypeLabels,
  loadActivityOptions,
  createActivityOption,
  dealOptions,
  entityOptions,
  defaultEntityId
}) {
  const t = useT();
  const [pending, setPending] = React.useState(false);
  const dictionaryAppearanceLabels = React.useMemo(
    () => ({
      colorLabel: t("customers.config.dictionaries.dialog.colorLabel", "Color"),
      colorHelp: t("customers.config.dictionaries.dialog.colorHelp", "Pick a highlight color for this entry."),
      colorClearLabel: t("customers.config.dictionaries.dialog.colorClear", "Remove color"),
      iconLabel: t("customers.config.dictionaries.dialog.iconLabel", "Icon or emoji"),
      iconPlaceholder: t("customers.config.dictionaries.dialog.iconPlaceholder", "Type an emoji or pick one of the suggestions."),
      iconPickerTriggerLabel: t("customers.config.dictionaries.dialog.iconBrowse", "Browse icons and emojis"),
      iconSearchPlaceholder: t("customers.config.dictionaries.dialog.iconSearchPlaceholder", "Search icons or emojis\u2026"),
      iconSearchEmptyLabel: t("customers.config.dictionaries.dialog.iconSearchEmpty", "No icons match your search."),
      iconSuggestionsLabel: t("customers.config.dictionaries.dialog.iconSuggestions", "Suggestions"),
      iconClearLabel: t("customers.config.dictionaries.dialog.iconClear", "Remove icon"),
      previewEmptyLabel: t("customers.config.dictionaries.dialog.previewEmpty", "No appearance selected")
    }),
    [t]
  );
  const normalizedDealOptions = React.useMemo(() => {
    if (!Array.isArray(dealOptions)) return [];
    const seen = /* @__PURE__ */ new Set();
    return dealOptions.map((option) => {
      if (!option || typeof option !== "object") return null;
      const id = typeof option.id === "string" ? option.id.trim() : "";
      if (!id || seen.has(id)) return null;
      const label = typeof option.label === "string" && option.label.trim().length ? option.label.trim() : id;
      seen.add(id);
      return { id, label };
    }).filter((option) => !!option);
  }, [dealOptions]);
  const normalizedEntityOptions = React.useMemo(() => {
    if (!Array.isArray(entityOptions)) return [];
    const seen = /* @__PURE__ */ new Set();
    return entityOptions.map((option) => {
      if (!option || typeof option !== "object") return null;
      const id = typeof option.id === "string" ? option.id.trim() : "";
      if (!id || seen.has(id)) return null;
      const label = typeof option.label === "string" && option.label.trim().length ? option.label.trim() : id;
      seen.add(id);
      return { id, label };
    }).filter((option) => !!option);
  }, [entityOptions]);
  const baseFields = React.useMemo(() => {
    const fields = [];
    if (normalizedEntityOptions.length) {
      fields.push({
        id: "entityId",
        label: t("customers.people.detail.activities.fields.entity", "Assign to customer"),
        type: "custom",
        layout: "half",
        component: ({ value, setValue }) => {
          const currentValue = typeof value === "string" && value.length ? value : normalizedEntityOptions[0]?.id ?? "";
          return /* @__PURE__ */ jsxs(
            Select,
            {
              value: currentValue || void 0,
              onValueChange: (next) => setValue(next ?? ""),
              children: [
                /* @__PURE__ */ jsx(SelectTrigger, { children: /* @__PURE__ */ jsx(SelectValue, {}) }),
                /* @__PURE__ */ jsx(SelectContent, { children: normalizedEntityOptions.map((option) => /* @__PURE__ */ jsx(SelectItem, { value: option.id, children: option.label }, option.id)) })
              ]
            }
          );
        }
      });
    }
    if (normalizedDealOptions.length) {
      fields.push({
        id: "dealId",
        label: t("customers.people.detail.activities.fields.deal", "Link to deal (optional)"),
        type: "custom",
        layout: "half",
        component: ({ value, setValue }) => {
          const currentValue = typeof value === "string" ? value : "";
          return /* @__PURE__ */ jsxs(
            Select,
            {
              value: currentValue || void 0,
              onValueChange: (next) => setValue(next ?? ""),
              children: [
                /* @__PURE__ */ jsx(SelectTrigger, { children: /* @__PURE__ */ jsx(SelectValue, { placeholder: t("customers.people.detail.activities.fields.dealPlaceholder", "No linked deal") }) }),
                /* @__PURE__ */ jsx(SelectContent, { children: normalizedDealOptions.map((option) => /* @__PURE__ */ jsx(SelectItem, { value: option.id, children: option.label }, option.id)) })
              ]
            }
          );
        }
      });
    }
    fields.push({
      id: "activityType",
      label: t("customers.people.detail.activities.fields.type"),
      type: "custom",
      required: true,
      layout: "half",
      component: ({ value, setValue }) => /* @__PURE__ */ jsx(
        DictionaryEntrySelect,
        {
          value: typeof value === "string" ? value : void 0,
          onChange: (next) => setValue(next ?? ""),
          fetchOptions: loadActivityOptions,
          createOption: createActivityOption,
          labels: activityTypeLabels,
          allowAppearance: true,
          allowInlineCreate: true,
          appearanceLabels: dictionaryAppearanceLabels,
          selectClassName: "w-full",
          sortOptions: "none",
          manageHref: "/backend/config/customers"
        }
      )
    });
    fields.push({
      id: "subject",
      label: t("customers.people.detail.activities.fields.subject"),
      type: "text",
      layout: "half",
      placeholder: t("customers.people.detail.activities.subjectPlaceholder", "Add a subject (optional)")
    });
    fields.push({
      id: "body",
      label: t("customers.people.detail.activities.fields.body"),
      type: "textarea",
      placeholder: t("customers.people.detail.activities.bodyPlaceholder", "Describe the interaction")
    });
    fields.push({
      id: "occurredAt",
      label: t("customers.people.detail.activities.fields.occurredAt"),
      type: "custom",
      component: ({ value, setValue }) => /* @__PURE__ */ jsx(
        "input",
        {
          type: "datetime-local",
          className: "w-full rounded-md border px-3 py-2 text-sm focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring",
          value: typeof value === "string" ? value : "",
          onChange: (event) => setValue(event.target.value || ""),
          onFocus: (event) => {
            const target = event.currentTarget;
            if (typeof target.showPicker === "function") {
              try {
                target.showPicker();
              } catch {
              }
            }
          },
          onClick: (event) => {
            const target = event.currentTarget;
            if (typeof target.showPicker === "function") {
              try {
                target.showPicker();
              } catch {
              }
            }
          }
        }
      ),
      layout: "half"
    });
    return fields;
  }, [
    activityTypeLabels,
    createActivityOption,
    dictionaryAppearanceLabels,
    loadActivityOptions,
    normalizedDealOptions,
    normalizedEntityOptions,
    t
  ]);
  const baseFieldIds = React.useMemo(() => new Set(baseFields.map((field) => field.id)), [baseFields]);
  const groups = React.useMemo(() => {
    const detailFields = [];
    if (normalizedEntityOptions.length) detailFields.push("entityId");
    if (normalizedDealOptions.length) detailFields.push("dealId");
    detailFields.push("activityType", "subject", "occurredAt", "body");
    return [
      {
        id: "details",
        title: t("customers.people.detail.activities.form.details", "Activity details"),
        column: 1,
        fields: detailFields
      },
      {
        id: "custom",
        title: t("customers.people.detail.activities.form.customFields", "Custom fields"),
        column: 2,
        kind: "customFields"
      }
    ];
  }, [normalizedDealOptions.length, normalizedEntityOptions.length, t]);
  const handleSubmit = React.useCallback(
    async (values) => {
      if (pending || isSubmitting) return;
      setPending(true);
      try {
        const parsed = schema.safeParse(values);
        if (!parsed.success) {
          throw buildActivityValidationError(parsed.error.issues, t);
        }
        const rawEntityId = typeof values.entityId === "string" ? values.entityId.trim() : "";
        const resolvedEntityId = rawEntityId || (typeof defaultEntityId === "string" ? defaultEntityId : "");
        const rawDealId = typeof values.dealId === "string" ? values.dealId.trim() : "";
        const base = {
          activityType: parsed.data.activityType,
          subject: parsed.data.subject || void 0,
          body: parsed.data.body || void 0,
          occurredAt: parsed.data.occurredAt && parsed.data.occurredAt.length ? new Date(parsed.data.occurredAt).toISOString() : void 0,
          dealId: rawDealId.length ? rawDealId : void 0
        };
        const reservedCustomKeys = /* @__PURE__ */ new Set(["entityId", "dealId"]);
        const customEntries = collectCustomFieldValues(values, {
          transform: (value) => normalizeCustomFieldSubmitValue(value),
          accept: (fieldId) => !reservedCustomKeys.has(fieldId)
        });
        Object.entries(values).forEach(([key, value]) => {
          if (key.startsWith("cf_")) return;
          if (!baseFieldIds.has(key) && key !== "id") {
            if (reservedCustomKeys.has(key)) return;
            customEntries[key] = normalizeCustomFieldSubmitValue(value);
          }
        });
        await onSubmit({ base, custom: customEntries, entityId: resolvedEntityId.length ? resolvedEntityId : void 0 });
      } finally {
        setPending(false);
      }
    },
    [baseFieldIds, defaultEntityId, isSubmitting, onSubmit, pending, t]
  );
  const embeddedInitialValues = React.useMemo(() => {
    const occurredAt = toLocalDateTimeInput(initialValues?.occurredAt ?? null);
    const resolvedEntity = (() => {
      const raw = typeof initialValues?.entityId === "string" ? initialValues.entityId : typeof defaultEntityId === "string" ? defaultEntityId : normalizedEntityOptions[0]?.id ?? "";
      return raw ?? "";
    })();
    const resolvedDeal = typeof initialValues?.dealId === "string" ? initialValues.dealId : "";
    return {
      entityId: resolvedEntity,
      dealId: resolvedDeal,
      activityType: initialValues?.activityType ?? "",
      subject: initialValues?.subject ?? "",
      body: initialValues?.body ?? "",
      occurredAt,
      ...Object.fromEntries(
        Object.entries(initialValues ?? {}).filter(([key]) => {
          if (!key.startsWith("cf_")) return false;
          const trimmed = key.slice(3);
          return trimmed !== "entityId" && trimmed !== "dealId";
        }).map(([key, value]) => [key, value])
      )
    };
  }, [defaultEntityId, initialValues, normalizedEntityOptions]);
  return /* @__PURE__ */ jsx(
    CrudForm,
    {
      embedded: true,
      fields: baseFields,
      groups,
      initialValues: embeddedInitialValues,
      onSubmit: handleSubmit,
      submitLabel: submitLabel ?? (mode === "edit" ? t("customers.people.detail.activities.update", "Update activity (\u2318/Ctrl + Enter)") : t("customers.people.detail.activities.save", "Save activity (\u2318/Ctrl + Enter)")),
      extraActions: /* @__PURE__ */ jsx(
        Button,
        {
          type: "button",
          variant: "outline",
          onClick: onCancel,
          disabled: pending || isSubmitting,
          children: cancelLabel ?? t("customers.people.detail.activities.cancel", "Cancel")
        }
      ),
      entityIds: ACTIVITY_ENTITY_IDS
    }
  );
}
function buildActivityValidationError(issues, t) {
  const issue = issues[0];
  const message = issue?.message ?? t("customers.people.detail.activities.error");
  const firstPath = Array.isArray(issue?.path) ? issue?.path?.[0] : void 0;
  const field = typeof firstPath === "string" ? firstPath : void 0;
  throw createCrudFormError(message, field ? { [field]: message } : void 0);
}
export {
  ActivityForm,
  buildActivityValidationError
};
//# sourceMappingURL=ActivityForm.js.map
