"use client";
import { Fragment, jsx, jsxs } from "react/jsx-runtime";
import * as React from "react";
import Link from "next/link";
import { AtSign, Briefcase, Loader2, Pencil, X } from "lucide-react";
import { Button } from "@open-mercato/ui/primitives/button";
import { MarkdownContent } from "@open-mercato/ui/backend/markdown";
import { flash } from "@open-mercato/ui/backend/FlashMessages";
import { useT } from "@open-mercato/shared/lib/i18n/context";
import { cn } from "@open-mercato/shared/lib/utils";
import { useQueryClient } from "@tanstack/react-query";
import { useOrganizationScopeVersion } from "@open-mercato/shared/lib/frontend/useOrganizationScope";
import { useEmailDuplicateCheck } from "../../backend/hooks/useEmailDuplicateCheck.js";
import { lookupPhoneDuplicate } from "../../utils/phoneDuplicates.js";
import {
  InlineMultilineEditor as UiInlineMultilineEditor,
  InlineTextEditor as UiInlineTextEditor,
  InlineSelectEditor as UiInlineSelectEditor
} from "@open-mercato/ui/backend/detail/InlineEditors";
import {
  DictionaryValue,
  ICON_SUGGESTIONS,
  renderDictionaryColor,
  renderDictionaryIcon
} from "../../lib/dictionaries.js";
import { DictionarySelectField } from "../formConfig.js";
import { AppearanceSelector } from "@open-mercato/core/modules/dictionaries/components/AppearanceSelector";
import { createDictionarySelectLabels } from "./utils.js";
import { formatDateTime } from "@open-mercato/shared/lib/time";
import {
  invalidateCustomerDictionary,
  useCustomerDictionary
} from "./hooks/useCustomerDictionary.js";
function InlineTextEditor(props) {
  const { type = "text", validator, recordId } = props;
  const t = useT();
  const normalizeText = React.useCallback((value) => {
    if (typeof value === "string") return value;
    if (value === null || value === void 0) return "";
    return String(value);
  }, []);
  const [draft, setDraft] = React.useState(() => normalizeText(props.value));
  const setDraftValue = React.useCallback((value) => {
    setDraft(normalizeText(value));
  }, [normalizeText]);
  const [editing, setEditing] = React.useState(false);
  const currentRecordId = React.useMemo(() => typeof recordId === "string" ? recordId : null, [recordId]);
  const isEmailField = type === "email";
  const isPhoneField = type === "tel";
  const trimmedDraft = React.useMemo(() => draft.trim(), [draft]);
  const validationError = React.useMemo(() => {
    if (!validator) return null;
    return validator(trimmedDraft);
  }, [trimmedDraft, validator]);
  const isValidEmailForLookup = React.useMemo(() => {
    if (!isEmailField) return false;
    if (!trimmedDraft.length) return false;
    return !validationError;
  }, [isEmailField, trimmedDraft, validationError]);
  const { duplicate: emailDuplicate, checking: emailChecking } = useEmailDuplicateCheck(draft, {
    recordId: currentRecordId,
    disabled: !editing || !isValidEmailForLookup,
    matchMode: "prefix"
  });
  const [phoneDuplicate, setPhoneDuplicate] = React.useState(null);
  const [phoneChecking, setPhoneChecking] = React.useState(false);
  React.useEffect(() => {
    if (!editing) {
      setDraftValue(props.value);
    }
  }, [editing, props.value, setDraftValue]);
  React.useEffect(() => {
    if (!editing || !isPhoneField) {
      setPhoneDuplicate(null);
      setPhoneChecking(false);
      return;
    }
    const digits = draft.replace(/\\D/g, "");
    if (digits.length < 7) {
      setPhoneDuplicate(null);
      setPhoneChecking(false);
      return;
    }
    let cancelled = false;
    setPhoneChecking(true);
    void lookupPhoneDuplicate(digits, { recordId: currentRecordId }).then((result) => {
      if (cancelled) return;
      setPhoneDuplicate(result);
    }).catch(() => {
      if (cancelled) return;
      setPhoneDuplicate(null);
    }).finally(() => {
      if (cancelled) return;
      setPhoneChecking(false);
    });
    return () => {
      cancelled = true;
    };
  }, [currentRecordId, draft, editing, isPhoneField]);
  return /* @__PURE__ */ jsx(
    UiInlineTextEditor,
    {
      ...props,
      type,
      validator,
      value: normalizeText(props.value),
      onDraftChange: setDraftValue,
      onEditingChange: setEditing,
      renderBelowInput: ({ resolvedType, error }) => {
        if (resolvedType === "email") {
          if (error || !editing || !isValidEmailForLookup) return null;
          if (emailDuplicate) {
            return /* @__PURE__ */ jsxs("p", { className: "text-xs text-muted-foreground", children: [
              t("customers.people.detail.inline.emailDuplicate", void 0, { name: emailDuplicate.displayName }),
              " ",
              /* @__PURE__ */ jsx(
                Link,
                {
                  className: "font-medium text-primary underline underline-offset-2",
                  href: `/backend/customers/people-v2/${emailDuplicate.id}`,
                  children: t("customers.people.detail.inline.emailDuplicateLink")
                }
              )
            ] });
          }
          if (emailChecking) {
            return /* @__PURE__ */ jsx("p", { className: "text-xs text-muted-foreground", children: t("customers.people.detail.inline.emailChecking") });
          }
        }
        if (resolvedType === "tel") {
          if (error || !editing) return null;
          if (phoneDuplicate) {
            return /* @__PURE__ */ jsxs("p", { className: "text-xs text-muted-foreground", children: [
              t("customers.people.form.phoneDuplicateNotice", void 0, { name: phoneDuplicate.label }),
              " ",
              phoneDuplicate.href ? /* @__PURE__ */ jsx(
                Link,
                {
                  className: "font-medium text-primary underline underline-offset-2",
                  href: phoneDuplicate.href,
                  children: t("customers.people.form.phoneDuplicateLink")
                }
              ) : null
            ] });
          }
          if (phoneChecking) {
            return /* @__PURE__ */ jsx("p", { className: "text-xs text-muted-foreground", children: t("customers.people.form.phoneChecking") });
          }
        }
        return null;
      }
    }
  );
}
const InlineMultilineEditor = UiInlineMultilineEditor;
const InlineSelectEditor = UiInlineSelectEditor;
function createSocialRenderDisplay(IconComponent) {
  return ({ value, emptyLabel }) => {
    const raw = typeof value === "string" ? value.trim() : "";
    if (!raw.length) {
      return /* @__PURE__ */ jsx("span", { className: "text-sm text-muted-foreground", children: emptyLabel });
    }
    const display = raw.replace(/^https?:\/\/(www\.)?/i, "").replace(/\/$/, "");
    return /* @__PURE__ */ jsxs(
      "a",
      {
        className: "inline-flex items-center gap-2 text-sm text-primary hover:text-primary/90 hover:underline",
        href: raw,
        target: "_blank",
        rel: "noreferrer",
        children: [
          /* @__PURE__ */ jsx(IconComponent, { "aria-hidden": true, className: "h-4 w-4" }),
          /* @__PURE__ */ jsx("span", { className: "truncate", children: display })
        ]
      }
    );
  };
}
const renderLinkedInDisplay = createSocialRenderDisplay(Briefcase);
const renderTwitterDisplay = createSocialRenderDisplay(AtSign);
const renderMultilineMarkdownDisplay = ({ value, emptyLabel }) => {
  const raw = typeof value === "string" ? value : "";
  const trimmed = raw.trim();
  if (!trimmed.length) {
    return /* @__PURE__ */ jsx("span", { className: "text-muted-foreground", children: emptyLabel });
  }
  return /* @__PURE__ */ jsx(
    MarkdownContent,
    {
      format: "markdown",
      body: raw,
      className: "text-sm text-foreground [&>*]:mb-2 [&>*:last-child]:mb-0 [&_ul]:ml-4 [&_ul]:list-disc [&_ol]:ml-4 [&_ol]:list-decimal [&_code]:rounded [&_code]:bg-muted [&_code]:px-1 [&_code]:py-0.5 [&_pre]:rounded-md [&_pre]:bg-muted [&_pre]:p-3 [&_pre]:text-xs"
    }
  );
};
function InlineDictionaryEditor({
  label,
  value,
  emptyLabel,
  onSave,
  kind,
  variant = "default",
  activateOnClick = false,
  containerClassName,
  triggerClassName,
  selectClassName
}) {
  const t = useT();
  const queryClient = useQueryClient();
  const translate = React.useCallback(
    (key, fallback) => {
      const result = t(key);
      return result === key ? fallback : result;
    },
    [t]
  );
  const dictionaryLabels = React.useMemo(() => createDictionarySelectLabels(kind, translate), [kind, translate]);
  const scopeVersion = useOrganizationScopeVersion();
  const dictionaryQuery = useCustomerDictionary(kind, scopeVersion);
  const dictionaryMap = dictionaryQuery.data?.map ?? null;
  const selectOptions = React.useMemo(() => {
    if (!dictionaryMap) return [];
    return Object.values(dictionaryMap).map((entry) => ({ value: entry.value, label: entry.label }));
  }, [dictionaryMap]);
  const handleSave = React.useCallback(
    async (nextValue) => {
      try {
        await onSave(nextValue);
        await invalidateCustomerDictionary(queryClient, kind);
      } catch (err) {
        const message = err instanceof Error ? err.message : t("customers.people.detail.inline.error");
        flash(message, "error");
      }
    },
    [kind, onSave, queryClient, t]
  );
  return /* @__PURE__ */ jsx(
    UiInlineSelectEditor,
    {
      label,
      value,
      emptyLabel,
      options: selectOptions,
      onSave: handleSave,
      variant,
      activateOnClick,
      containerClassName,
      triggerClassName,
      hideLabel: false,
      renderEditor: ({ value: selectValue, onChange }) => /* @__PURE__ */ jsxs(Fragment, { children: [
        /* @__PURE__ */ jsx(
          DictionarySelectField,
          {
            kind,
            value: selectValue.length ? selectValue : void 0,
            onChange: (next) => onChange(next ?? ""),
            labels: dictionaryLabels,
            selectClassName
          }
        ),
        dictionaryQuery.isError ? /* @__PURE__ */ jsx("p", { className: "text-xs text-status-error-text", children: dictionaryQuery.error instanceof Error ? dictionaryQuery.error.message : translate("customers.people.form.dictionary.errorLoad", "Failed to load options") }) : null
      ] }),
      renderDisplay: ({ value: currentValue }) => {
        if (dictionaryMap) {
          return /* @__PURE__ */ jsx(
            DictionaryValue,
            {
              value: currentValue,
              map: dictionaryMap,
              fallback: /* @__PURE__ */ jsx("span", { className: "text-sm text-muted-foreground", children: emptyLabel }),
              className: "text-sm",
              iconWrapperClassName: "inline-flex h-6 w-6 items-center justify-center rounded border border-border bg-card",
              iconClassName: "h-4 w-4",
              colorClassName: "h-3 w-3 rounded-full"
            }
          );
        }
        if (currentValue && currentValue.length) {
          return /* @__PURE__ */ jsx("span", { className: "break-words text-sm", children: currentValue });
        }
        if (dictionaryQuery.isLoading) {
          return /* @__PURE__ */ jsx("span", { className: "text-sm text-muted-foreground", children: translate("customers.people.form.dictionary.loading", "Loading\u2026") });
        }
        return /* @__PURE__ */ jsx("span", { className: "text-sm text-muted-foreground", children: emptyLabel });
      }
    }
  );
}
function InlineNextInteractionEditor({
  label,
  valueAt,
  valueName,
  valueRefId,
  valueIcon,
  valueColor,
  emptyLabel,
  onSave,
  activateOnClick = false
}) {
  const t = useT();
  const [editing, setEditing] = React.useState(false);
  const [draftDate, setDraftDate] = React.useState(() => valueAt ? valueAt.slice(0, 16) : "");
  const [draftName, setDraftName] = React.useState(valueName ?? "");
  const [draftRefId, setDraftRefId] = React.useState(valueRefId ?? "");
  const [draftIcon, setDraftIcon] = React.useState(valueIcon ?? "");
  const [draftColor, setDraftColor] = React.useState(valueColor ?? null);
  const [dateError, setDateError] = React.useState(null);
  const [nameError, setNameError] = React.useState(null);
  const [submitError, setSubmitError] = React.useState(null);
  const [saving, setSaving] = React.useState(false);
  const formRef = React.useRef(null);
  const dateErrorId = React.useId();
  const nameErrorId = React.useId();
  const containerClasses = cn("group relative rounded-lg border p-4", activateOnClick && !editing ? "cursor-pointer" : null);
  const requiredMessage = React.useMemo(
    () => t("customers.people.detail.inline.required", "This field is required"),
    [t]
  );
  React.useEffect(() => {
    if (!editing) {
      setDraftDate(valueAt ? valueAt.slice(0, 16) : "");
      setDraftName(valueName ?? "");
      setDraftRefId(valueRefId ?? "");
      setDraftIcon(valueIcon ?? "");
      setDraftColor(valueColor ?? null);
      setDateError(null);
      setNameError(null);
      setSubmitError(null);
    }
  }, [editing, valueAt, valueName, valueRefId, valueIcon, valueColor]);
  const appearanceLabels = React.useMemo(
    () => ({
      colorLabel: t("customers.people.detail.inline.nextInteractionColorLabel"),
      colorHelp: t("customers.people.detail.inline.nextInteractionColorHelp"),
      colorClearLabel: t("customers.people.detail.inline.nextInteractionColorClear"),
      iconLabel: t("customers.people.detail.inline.nextInteractionIconLabel"),
      iconPlaceholder: t("customers.people.detail.inline.nextInteractionIconPlaceholder"),
      iconPickerTriggerLabel: t("customers.people.detail.inline.nextInteractionIconBrowse"),
      iconSearchPlaceholder: t("customers.people.detail.inline.nextInteractionIconSearchPlaceholder"),
      iconSearchEmptyLabel: t("customers.people.detail.inline.nextInteractionIconSearchEmpty"),
      iconSuggestionsLabel: t("customers.people.detail.inline.nextInteractionIconSuggestions"),
      iconClearLabel: t("customers.people.detail.inline.nextInteractionIconClear"),
      previewEmptyLabel: t("customers.people.detail.inline.nextInteractionAppearanceEmpty")
    }),
    [t]
  );
  const handleSave = React.useCallback(async () => {
    setSubmitError(null);
    setDateError(null);
    setNameError(null);
    const trimmedName = draftName.trim();
    let hasError = false;
    if (!draftDate) {
      setDateError(requiredMessage);
      hasError = true;
    }
    if (!trimmedName.length) {
      setNameError(requiredMessage);
      hasError = true;
    }
    if (hasError) return;
    const parsedDate = new Date(draftDate);
    if (Number.isNaN(parsedDate.getTime())) {
      setDateError(t("customers.people.detail.inline.nextInteractionInvalid"));
      return;
    }
    const iso = parsedDate.toISOString();
    const trimmedRef = draftRefId.trim();
    const trimmedIcon = draftIcon.trim();
    const normalizedColor = (() => {
      if (!draftColor) return null;
      const trimmed = draftColor.trim().toLowerCase();
      return /^#([0-9a-f]{6})$/.test(trimmed) ? trimmed : null;
    })();
    setSaving(true);
    try {
      await onSave({
        at: iso,
        name: trimmedName,
        refId: trimmedRef.length ? trimmedRef : null,
        icon: trimmedIcon.length ? trimmedIcon : null,
        color: normalizedColor
      });
      setEditing(false);
    } catch (err) {
      const message = err instanceof Error ? err.message : t("customers.people.detail.inline.error");
      setSubmitError(message);
    } finally {
      setSaving(false);
    }
  }, [draftColor, draftDate, draftIcon, draftName, draftRefId, onSave, requiredMessage, t]);
  const handleFormSubmit = React.useCallback(
    (event) => {
      event.preventDefault();
      if (saving) return;
      void handleSave();
    },
    [handleSave, saving]
  );
  const handleFormKeyDown = React.useCallback(
    (event) => {
      if (event.key === "Escape") {
        event.preventDefault();
        setEditing(false);
        return;
      }
      if (event.key === "Enter" && (event.metaKey || event.ctrlKey)) {
        event.preventDefault();
        if (saving) return;
        try {
          formRef.current?.requestSubmit();
        } catch {
          void handleSave();
        }
      }
    },
    [handleSave, saving]
  );
  const handleActivate = React.useCallback(() => {
    if (!editing) setEditing(true);
  }, [editing]);
  const handleKeyDown = React.useCallback(
    (event) => {
      if (!activateOnClick || editing) return;
      if (event.key === "Enter" || event.key === " ") {
        event.preventDefault();
        handleActivate();
      }
    },
    [activateOnClick, editing, handleActivate]
  );
  const handleInteractiveClick = React.useCallback(
    (event) => {
      if (!activateOnClick || editing) return;
      const target = event.target;
      const interactiveElement = target.closest('button, input, select, textarea, a, [role="link"]');
      if (interactiveElement) {
        if (interactiveElement.tagName.toLowerCase() === "a") {
          if (event.metaKey || event.ctrlKey || event.shiftKey || event.altKey) {
            return;
          }
          event.preventDefault();
        } else {
          return;
        }
      }
      handleActivate();
    },
    [activateOnClick, editing, handleActivate]
  );
  const interactiveProps = activateOnClick && !editing ? {
    role: "button",
    tabIndex: 0,
    onClick: handleInteractiveClick,
    onKeyDown: handleKeyDown
  } : {};
  return /* @__PURE__ */ jsxs("div", { className: containerClasses, onClick: handleInteractiveClick, children: [
    /* @__PURE__ */ jsx(
      Button,
      {
        type: "button",
        variant: "ghost",
        size: "sm",
        className: cn(
          "absolute right-3 top-3 transition-opacity duration-150",
          editing ? "opacity-100" : "opacity-0 group-hover:opacity-100 group-focus-within:opacity-100 focus-visible:opacity-100"
        ),
        onClick: (event) => {
          event.stopPropagation();
          setEditing((state) => !state);
        },
        children: editing ? /* @__PURE__ */ jsx(X, { className: "h-4 w-4" }) : /* @__PURE__ */ jsx(Pencil, { className: "h-4 w-4" })
      }
    ),
    /* @__PURE__ */ jsx("div", { className: "flex items-start gap-2", ...interactiveProps, children: /* @__PURE__ */ jsxs("div", { className: "flex-1", children: [
      /* @__PURE__ */ jsx("p", { className: "text-xs uppercase tracking-wide text-muted-foreground", children: label }),
      editing ? /* @__PURE__ */ jsxs(
        "form",
        {
          ref: formRef,
          className: "mt-2 space-y-4",
          onSubmit: handleFormSubmit,
          onKeyDown: handleFormKeyDown,
          children: [
            /* @__PURE__ */ jsx(
              "input",
              {
                type: "datetime-local",
                className: cn(
                  "w-full rounded-md border px-3 py-2 text-sm focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring",
                  dateError ? "border-destructive aria-invalid:border-destructive aria-invalid:ring-destructive" : null
                ),
                value: draftDate,
                "aria-invalid": dateError ? "true" : void 0,
                "aria-required": "true",
                "aria-describedby": dateError ? dateErrorId : void 0,
                onChange: (event) => {
                  if (dateError) setDateError(null);
                  if (submitError) setSubmitError(null);
                  setDraftDate(event.target.value);
                }
              }
            ),
            dateError ? /* @__PURE__ */ jsx("p", { id: dateErrorId, className: "text-xs text-destructive", children: dateError }) : null,
            /* @__PURE__ */ jsx(
              "input",
              {
                placeholder: t("customers.people.detail.inline.nextInteractionName"),
                className: cn(
                  "w-full rounded-md border px-3 py-2 text-sm focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring",
                  nameError ? "border-destructive aria-invalid:border-destructive aria-invalid:ring-destructive" : null
                ),
                value: draftName,
                "aria-invalid": nameError ? "true" : void 0,
                "aria-required": "true",
                "aria-describedby": nameError ? nameErrorId : void 0,
                onChange: (event) => {
                  if (submitError) setSubmitError(null);
                  if (nameError) setNameError(null);
                  setDraftName(event.target.value);
                }
              }
            ),
            nameError ? /* @__PURE__ */ jsx("p", { id: nameErrorId, className: "text-xs text-destructive", children: nameError }) : null,
            /* @__PURE__ */ jsx(
              "input",
              {
                placeholder: t("customers.people.detail.inline.nextInteractionRef"),
                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: draftRefId,
                onChange: (event) => {
                  if (submitError) setSubmitError(null);
                  setDraftRefId(event.target.value);
                }
              }
            ),
            /* @__PURE__ */ jsx(
              AppearanceSelector,
              {
                icon: draftIcon || null,
                color: draftColor,
                onIconChange: (next) => {
                  if (submitError) setSubmitError(null);
                  setDraftIcon(next ?? "");
                },
                onColorChange: (next) => {
                  if (submitError) setSubmitError(null);
                  setDraftColor(next);
                },
                iconSuggestions: ICON_SUGGESTIONS,
                disabled: saving,
                labels: appearanceLabels
              }
            ),
            submitError && !dateError && !nameError ? /* @__PURE__ */ jsx("p", { className: "text-xs text-destructive", children: submitError }) : null,
            /* @__PURE__ */ jsxs("div", { className: "flex flex-wrap items-center gap-2", children: [
              /* @__PURE__ */ jsxs(Button, { type: "submit", size: "sm", disabled: saving, children: [
                saving ? /* @__PURE__ */ jsx(Loader2, { className: "mr-2 h-3.5 w-3.5 animate-spin" }) : null,
                t("customers.people.detail.inline.saveShortcut", "Save \u2318\u23CE / Ctrl+Enter")
              ] }),
              /* @__PURE__ */ jsx(Button, { type: "button", size: "sm", variant: "ghost", onClick: () => setEditing(false), disabled: saving, children: t("customers.people.detail.inline.cancel") }),
              /* @__PURE__ */ jsx(
                Button,
                {
                  type: "button",
                  size: "sm",
                  variant: "secondary",
                  onClick: async () => {
                    setDraftDate("");
                    setDraftName("");
                    setDraftRefId("");
                    setDraftIcon("");
                    setDraftColor(null);
                    setDateError(null);
                    setNameError(null);
                    setSubmitError(null);
                    setSaving(true);
                    try {
                      await onSave(null);
                      setEditing(false);
                    } catch (err) {
                      const message = err instanceof Error ? err.message : t("customers.people.detail.inline.error");
                      setSubmitError(message);
                    } finally {
                      setSaving(false);
                    }
                  },
                  disabled: saving,
                  children: t("customers.people.detail.inline.clear")
                }
              )
            ] })
          ]
        }
      ) : /* @__PURE__ */ jsx("div", { className: "mt-1 text-sm", children: valueAt ? /* @__PURE__ */ jsxs("div", { className: "flex items-start gap-3", children: [
        valueIcon ? /* @__PURE__ */ jsx("span", { className: "inline-flex h-8 w-8 items-center justify-center rounded border border-border bg-card", children: renderDictionaryIcon(valueIcon, "h-4 w-4") }) : null,
        /* @__PURE__ */ jsxs("div", { className: "flex-1", children: [
          /* @__PURE__ */ jsx("span", { className: "block", children: formatDateTime(valueAt) }),
          valueName ? /* @__PURE__ */ jsx("span", { className: "text-xs text-muted-foreground", children: valueName }) : null,
          valueRefId ? /* @__PURE__ */ jsxs("span", { className: "text-xs text-muted-foreground", children: [
            "#",
            valueRefId
          ] }) : null
        ] }),
        valueColor ? renderDictionaryColor(valueColor, "h-3 w-3 rounded-full border border-border") : null
      ] }) : /* @__PURE__ */ jsx("span", { className: "text-muted-foreground", children: emptyLabel }) })
    ] }) })
  ] });
}
export {
  InlineDictionaryEditor,
  InlineMultilineEditor,
  InlineNextInteractionEditor,
  InlineSelectEditor,
  InlineTextEditor,
  renderLinkedInDisplay,
  renderMultilineMarkdownDisplay,
  renderTwitterDisplay
};
//# sourceMappingURL=InlineEditors.js.map
