"use client";
import { Fragment, jsx, jsxs } from "react/jsx-runtime";
import * as React from "react";
import { SquarePen, Calendar, Check, ChevronDown, ChevronUp } from "lucide-react";
import { z } from "zod";
import { useT } from "@open-mercato/shared/lib/i18n/context";
import { apiCallOrThrow } from "@open-mercato/ui/backend/utils/apiCall";
import { flash } from "@open-mercato/ui/backend/FlashMessages";
import { Button } from "@open-mercato/ui/primitives/button";
import { usePersistedBooleanFlag } from "@open-mercato/ui/backend/crud/usePersistedBooleanFlag";
import { ActivityTypeSelector } from "./ActivityTypeSelector.js";
import { MiniWeekCalendar } from "./MiniWeekCalendar.js";
import { createLogger } from "@open-mercato/shared/lib/logger";
const logger = createLogger("customers");
const composerSchema = z.object({
  description: z.string().trim().min(1, "customers.activityComposer.validation.descriptionRequired"),
  occurredAt: z.string().min(1)
});
function formatDateBadge(isoLocal, t) {
  if (!isoLocal) return "";
  const now = /* @__PURE__ */ new Date();
  const date = new Date(isoLocal.replace("T", " "));
  const time = isoLocal.slice(11, 16);
  const isToday = date.getFullYear() === now.getFullYear() && date.getMonth() === now.getMonth() && date.getDate() === now.getDate();
  const dayLabel = isToday ? t("customers.activityComposer.today", "Today") : date.toLocaleDateString(void 0, { day: "numeric", month: "short" });
  return `${dayLabel} \xB7 ${time}`;
}
function InlineActivityComposer({
  entityType,
  entityId,
  dealId = null,
  onActivityCreated,
  runGuardedMutation,
  onScheduleRequested,
  useCanonicalInteractions
}) {
  const t = useT();
  const calendarRefreshRef = React.useRef(null);
  const [selectedType, setSelectedType] = React.useState("call");
  const [description, setDescription] = React.useState("");
  const [occurredAt, setOccurredAt] = React.useState(() => (/* @__PURE__ */ new Date()).toISOString().slice(0, 16));
  const [scheduledAt, setScheduledAt] = React.useState("");
  const [saving, setSaving] = React.useState(false);
  const [errors, setErrors] = React.useState({});
  const descriptionRef = React.useRef(null);
  const weekPreviewStorageKey = `om:inline-composer:week-preview:${entityType}`;
  const { value: weekPreviewHidden, toggle: toggleWeekPreview } = usePersistedBooleanFlag(
    weekPreviewStorageKey,
    false
  );
  const resizeDescription = React.useCallback(() => {
    const el = descriptionRef.current;
    if (!el) return;
    el.style.height = "auto";
    const maxHeight = 200;
    el.style.height = `${Math.min(el.scrollHeight, maxHeight)}px`;
  }, []);
  React.useEffect(() => {
    resizeDescription();
  }, [description, resizeDescription]);
  const handleTypeSelect = React.useCallback((type) => {
    setSelectedType((previous) => previous === type ? null : type);
    setErrors({});
  }, []);
  const handleReset = React.useCallback(() => {
    setDescription("");
    setOccurredAt((/* @__PURE__ */ new Date()).toISOString().slice(0, 16));
    setScheduledAt("");
    setErrors({});
  }, []);
  const handleSave = React.useCallback(async () => {
    if (!selectedType) {
      setErrors({ type: t("customers.activityComposer.validation.typeRequired", "Select an activity type") });
      return;
    }
    const result = composerSchema.safeParse({ description, occurredAt });
    if (!result.success) {
      const fieldErrors = {};
      for (const issue of result.error.issues) {
        const field = issue.path[0];
        if (field) fieldErrors[String(field)] = t(issue.message);
      }
      setErrors(fieldErrors);
      return;
    }
    setSaving(true);
    setErrors({});
    try {
      const mutationPayload = {
        entityId,
        dealId,
        interactionType: selectedType,
        body: description.trim(),
        status: scheduledAt ? "planned" : "done",
        occurredAt: scheduledAt ? null : new Date(occurredAt).toISOString(),
        scheduledAt: scheduledAt ? new Date(scheduledAt).toISOString() : null
      };
      const operation = () => apiCallOrThrow("/api/customers/interactions", {
        method: "POST",
        headers: { "content-type": "application/json" },
        body: JSON.stringify(mutationPayload)
      });
      if (runGuardedMutation) {
        await runGuardedMutation(operation, mutationPayload);
      } else {
        await operation();
      }
      flash(
        t("customers.activityComposer.saved", {
          type: t(`customers.activityComposer.types.${selectedType}`)
        }),
        "success"
      );
      handleReset();
      calendarRefreshRef.current?.();
      onActivityCreated?.();
    } catch (error) {
      logger.error("customers.inlineActivityComposer.save failed", { err: error });
      flash(t("customers.activityComposer.error", "Failed to save activity"), "error");
    } finally {
      setSaving(false);
    }
  }, [
    description,
    dealId,
    entityId,
    handleReset,
    occurredAt,
    onActivityCreated,
    runGuardedMutation,
    scheduledAt,
    selectedType,
    t
  ]);
  const handleKeyDown = React.useCallback((event) => {
    if ((event.metaKey || event.ctrlKey) && event.key === "Enter") {
      event.preventDefault();
      handleSave();
    }
  }, [handleSave]);
  return /* @__PURE__ */ jsxs("div", { className: "rounded-2xl border border-border/70 bg-card p-5", onKeyDown: handleKeyDown, children: [
    /* @__PURE__ */ jsxs("div", { className: "mb-4 flex items-center justify-between", children: [
      /* @__PURE__ */ jsxs("h3", { className: "flex items-center gap-2 text-base font-semibold text-foreground", children: [
        /* @__PURE__ */ jsx(SquarePen, { className: "size-4" }),
        t("customers.activityComposer.title", "Log activity")
      ] }),
      /* @__PURE__ */ jsxs("div", { className: "flex items-center gap-2", children: [
        onScheduleRequested ? /* @__PURE__ */ jsxs(Button, { type: "button", variant: "outline", size: "sm", onClick: onScheduleRequested, disabled: saving, children: [
          /* @__PURE__ */ jsx(Calendar, { className: "size-4" }),
          t("customers.activityComposer.schedule", "Schedule")
        ] }) : null,
        /* @__PURE__ */ jsxs(
          Button,
          {
            type: "button",
            size: "sm",
            onClick: handleSave,
            disabled: saving || !selectedType,
            children: [
              /* @__PURE__ */ jsx(Check, { className: "size-4" }),
              saving ? t("customers.activityComposer.saving", "Saving...") : t("customers.activityComposer.saveActivity", "Save activity")
            ]
          }
        )
      ] })
    ] }),
    /* @__PURE__ */ jsx(ActivityTypeSelector, { selectedType, onSelect: handleTypeSelect }),
    /* @__PURE__ */ jsxs("div", { className: "mt-4 flex items-start gap-3", children: [
      /* @__PURE__ */ jsxs("div", { className: "flex-1", children: [
        /* @__PURE__ */ jsx(
          "label",
          {
            htmlFor: "inline-activity-composer-description",
            className: "mb-1 block text-xs font-medium text-muted-foreground",
            children: t("customers.activityComposer.descriptionLabel", "Description")
          }
        ),
        /* @__PURE__ */ jsx(
          "textarea",
          {
            ref: descriptionRef,
            id: "inline-activity-composer-description",
            value: description,
            onChange: (event) => setDescription(event.target.value),
            placeholder: t("customers.activityComposer.descriptionPlaceholder", "What happened?"),
            className: "min-h-[72px] w-full resize-none rounded-lg border bg-background px-3 py-2.5 text-sm placeholder:text-muted-foreground focus:outline-none focus:ring-1 focus:ring-ring",
            rows: 3
          }
        ),
        errors.description ? /* @__PURE__ */ jsx("p", { className: "mt-1 text-xs text-destructive", children: errors.description }) : null
      ] }),
      /* @__PURE__ */ jsxs("label", { className: "mt-[22px] flex shrink-0 cursor-pointer items-center gap-2 rounded-lg border bg-background px-3 py-2.5 text-sm text-muted-foreground", children: [
        /* @__PURE__ */ jsx(Calendar, { className: "size-4" }),
        /* @__PURE__ */ jsx("span", { className: "text-sm font-medium text-foreground", children: formatDateBadge(occurredAt, t) }),
        /* @__PURE__ */ jsx(
          "input",
          {
            type: "datetime-local",
            value: occurredAt,
            onChange: (event) => setOccurredAt(event.target.value),
            className: "sr-only"
          }
        )
      ] })
    ] }),
    /* @__PURE__ */ jsxs("div", { className: "mt-4", children: [
      /* @__PURE__ */ jsxs("div", { className: "mb-2 flex items-center justify-between", children: [
        /* @__PURE__ */ jsx("span", { className: "text-xs font-medium uppercase tracking-wide text-muted-foreground", children: t("customers.activityComposer.weekPreviewTitle", "This week") }),
        /* @__PURE__ */ jsx(
          Button,
          {
            type: "button",
            variant: "ghost",
            size: "sm",
            onClick: toggleWeekPreview,
            "aria-expanded": !weekPreviewHidden,
            "aria-controls": "inline-activity-composer-week-preview",
            className: "h-auto px-2 py-1 text-xs text-muted-foreground hover:text-foreground",
            children: weekPreviewHidden ? /* @__PURE__ */ jsxs(Fragment, { children: [
              /* @__PURE__ */ jsx(ChevronDown, { className: "mr-1 size-3" }),
              t("customers.activityComposer.showWeekPreview", "Show week preview")
            ] }) : /* @__PURE__ */ jsxs(Fragment, { children: [
              /* @__PURE__ */ jsx(ChevronUp, { className: "mr-1 size-3" }),
              t("customers.activityComposer.hideWeekPreview", "Hide week preview")
            ] })
          }
        )
      ] }),
      !weekPreviewHidden ? /* @__PURE__ */ jsx("div", { id: "inline-activity-composer-week-preview", children: /* @__PURE__ */ jsx(
        MiniWeekCalendar,
        {
          entityId,
          useCanonicalInteractions,
          refreshRef: calendarRefreshRef
        }
      ) }) : null
    ] }),
    scheduledAt || false ? /* @__PURE__ */ jsxs("div", { className: "mt-3 flex items-center gap-2", children: [
      /* @__PURE__ */ jsx("label", { className: "text-xs text-muted-foreground", children: t("customers.activityComposer.scheduledLabel", "Scheduled for") }),
      /* @__PURE__ */ jsx(
        "input",
        {
          type: "datetime-local",
          value: scheduledAt,
          onChange: (event) => setScheduledAt(event.target.value),
          className: "rounded-md border bg-background px-3 py-1.5 text-sm focus:outline-none focus:ring-1 focus:ring-ring"
        }
      )
    ] }) : null
  ] });
}
export {
  InlineActivityComposer
};
//# sourceMappingURL=InlineActivityComposer.js.map
