"use client";
import { Fragment, jsx, jsxs } from "react/jsx-runtime";
import * as React from "react";
import { Plus, Pencil, Trash2, RefreshCw, Languages } from "lucide-react";
import { Button } from "@open-mercato/ui/primitives/button";
import { Input } from "@open-mercato/ui/primitives/input";
import {
  Dialog,
  DialogContent,
  DialogFooter,
  DialogHeader,
  DialogTitle
} from "@open-mercato/ui/primitives/dialog";
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@open-mercato/ui/primitives/table";
import { Spinner } from "@open-mercato/ui/primitives/spinner";
import { flash } from "@open-mercato/ui/backend/FlashMessages";
import { apiCall, withScopedApiRequestHeaders } from "@open-mercato/ui/backend/utils/apiCall";
import { buildOptimisticLockHeader } from "@open-mercato/ui/backend/utils/optimisticLock";
import { surfaceRecordConflict } from "@open-mercato/ui/backend/conflicts";
import { useGuardedMutation } from "@open-mercato/ui/backend/injection/useGuardedMutation";
import { useQueryClient } from "@tanstack/react-query";
import { useOrganizationScopeVersion } from "@open-mercato/shared/lib/frontend/useOrganizationScope";
import { useT } from "@open-mercato/shared/lib/i18n/context";
import { useConfirmDialog } from "@open-mercato/ui/backend/confirm-dialog";
import { AppearanceSelector, useAppearanceState } from "./AppearanceSelector.js";
import { DictionaryValue } from "./dictionaryAppearance.js";
import {
  invalidateDictionaryEntries,
  useDictionaryEntries
} from "./hooks/useDictionaryEntries.js";
import {
  DialogDescription
} from "@open-mercato/ui/primitives/dialog";
import { TranslationManager } from "@open-mercato/core/modules/translations/components/TranslationManager";
import { createLogger } from "@open-mercato/shared/lib/logger";
const logger = createLogger("dictionaries").child({ component: "DictionaryEntriesEditor" });
function DictionaryEntriesEditor({ dictionaryId, dictionaryName, readOnly = false }) {
  const t = useT();
  const { confirm, ConfirmDialogElement } = useConfirmDialog();
  const readOnlyMessage = t("dictionaries.config.entries.readOnly", "Inherited dictionaries are managed at the parent organization.");
  const queryClient = useQueryClient();
  const scopeVersion = useOrganizationScopeVersion();
  const dictionaryQuery = useDictionaryEntries(dictionaryId, scopeVersion);
  const entries = React.useMemo(() => dictionaryQuery.data?.fullEntries ?? [], [dictionaryQuery.data?.fullEntries]);
  const dictionaryMap = dictionaryQuery.data?.map ?? {};
  const isInitialLoading = dictionaryQuery.isLoading;
  const loadError = dictionaryQuery.isError ? t("dictionaries.config.entries.error.load", "Failed to load dictionary entries.") : null;
  const [dialogOpen, setDialogOpen] = React.useState(false);
  const [isDeleting, setIsDeleting] = React.useState(false);
  const [isSaving, setIsSaving] = React.useState(false);
  const [formState, setFormState] = React.useState(() => ({
    value: "",
    label: "",
    color: null,
    icon: null
  }));
  const [errors, setErrors] = React.useState({});
  const [translateEntry, setTranslateEntry] = React.useState(null);
  const appearance = useAppearanceState(formState.icon, formState.color);
  const mutationContextId = React.useMemo(
    () => `dictionaries:dictionary_entry:${dictionaryId}`,
    [dictionaryId]
  );
  const { runMutation, retryLastMutation } = useGuardedMutation({
    contextId: mutationContextId,
    blockedMessage: t("ui.forms.flash.saveBlocked", "Save blocked by validation")
  });
  const resetForm = React.useCallback(() => {
    setFormState({ value: "", label: "", color: null, icon: null });
    appearance.setColor(null);
    appearance.setIcon(null);
    setErrors({});
  }, [appearance]);
  const openDialog = React.useCallback(
    (entry) => {
      if (readOnly) {
        flash(readOnlyMessage, "info");
        return;
      }
      if (entry) {
        setFormState({
          id: entry.id,
          value: entry.value,
          label: entry.label,
          color: entry.color ?? null,
          icon: entry.icon ?? null,
          updatedAt: entry.updatedAt ?? null
        });
        appearance.setColor(entry.color ?? null);
        appearance.setIcon(entry.icon ?? null);
      } else {
        resetForm();
      }
      setErrors({});
      setDialogOpen(true);
    },
    [appearance, readOnly, readOnlyMessage, resetForm]
  );
  const closeDialog = React.useCallback(() => {
    setDialogOpen(false);
    resetForm();
    setErrors({});
  }, [resetForm]);
  const handleSave = React.useCallback(async () => {
    if (readOnly) {
      flash(readOnlyMessage, "info");
      return;
    }
    const trimmedValue = formState.value.trim();
    const trimmedLabel = formState.label.trim();
    const nextErrors = {};
    if (!trimmedValue) {
      nextErrors.value = t("dictionaries.config.entries.error.required", "Value is required.");
    }
    if (nextErrors.value) {
      setErrors(nextErrors);
      return;
    }
    setErrors({});
    setIsSaving(true);
    try {
      const payload = {
        value: trimmedValue,
        label: trimmedLabel || trimmedValue,
        color: appearance.color,
        icon: appearance.icon
      };
      if (formState.id) {
        const entryId = formState.id;
        const expectedUpdatedAt = formState.updatedAt;
        await runMutation({
          operation: () => withScopedApiRequestHeaders(
            buildOptimisticLockHeader(expectedUpdatedAt),
            async () => {
              const call = await apiCall(
                `/api/dictionaries/${dictionaryId}/entries/${entryId}`,
                {
                  method: "PATCH",
                  headers: { "content-type": "application/json" },
                  body: JSON.stringify(payload)
                }
              );
              if (!call.ok) {
                throw Object.assign(
                  new Error(typeof call.result?.error === "string" ? call.result.error : "Failed to save dictionary entry"),
                  { status: call.status, ...call.result && typeof call.result === "object" ? call.result : {} }
                );
              }
              return call;
            }
          ),
          context: {
            formId: mutationContextId,
            resourceKind: "dictionaries.dictionary_entry",
            resourceId: entryId,
            retryLastMutation
          },
          mutationPayload: payload
        });
        flash(t("dictionaries.config.entries.success.update", "Dictionary entry updated."), "success");
      } else {
        await runMutation({
          operation: async () => {
            const call = await apiCall(
              `/api/dictionaries/${dictionaryId}/entries`,
              {
                method: "POST",
                headers: { "content-type": "application/json" },
                body: JSON.stringify(payload)
              }
            );
            if (!call.ok) {
              throw new Error(
                typeof call.result?.error === "string" ? call.result.error : "Failed to create dictionary entry"
              );
            }
            return call;
          },
          context: {
            formId: mutationContextId,
            resourceKind: "dictionaries.dictionary_entry",
            retryLastMutation
          },
          mutationPayload: payload
        });
        flash(t("dictionaries.config.entries.success.create", "Dictionary entry created."), "success");
      }
      await invalidateDictionaryEntries(queryClient, dictionaryId);
      setDialogOpen(false);
      setFormState({ value: "", label: "", color: null, icon: null });
      appearance.setColor(null);
      appearance.setIcon(null);
      setErrors({});
    } catch (err) {
      if (surfaceRecordConflict(err, t)) {
        return;
      }
      logger.error("Failed to save dictionary entry", { err });
      flash(t("dictionaries.config.entries.error.save", "Failed to save dictionary entry."), "error");
    } finally {
      setIsSaving(false);
    }
  }, [appearance, dictionaryId, formState.id, formState.label, formState.updatedAt, formState.value, mutationContextId, queryClient, readOnly, readOnlyMessage, runMutation, retryLastMutation, t]);
  const handleDelete = React.useCallback(
    async (entry) => {
      if (readOnly) {
        flash(readOnlyMessage, "info");
        return;
      }
      if (!entry.id) return;
      const confirmDelete = await confirm({
        title: t("dictionaries.config.entries.delete.confirm", 'Delete "{{value}}"?', { value: entry.label || entry.value }),
        variant: "destructive"
      });
      if (!confirmDelete) return;
      setIsDeleting(true);
      try {
        await runMutation({
          operation: () => withScopedApiRequestHeaders(
            buildOptimisticLockHeader(entry.updatedAt),
            async () => {
              const call = await apiCall(
                `/api/dictionaries/${dictionaryId}/entries/${entry.id}`,
                { method: "DELETE" }
              );
              if (!call.ok) {
                throw Object.assign(
                  new Error(
                    typeof call.result?.error === "string" ? call.result.error : "Failed to delete dictionary entry"
                  ),
                  { status: call.status, ...call.result && typeof call.result === "object" ? call.result : {} }
                );
              }
              return call;
            }
          ),
          context: {
            formId: mutationContextId,
            resourceKind: "dictionaries.dictionary_entry",
            resourceId: entry.id,
            retryLastMutation
          },
          mutationPayload: { id: entry.id }
        });
        await invalidateDictionaryEntries(queryClient, dictionaryId);
        flash(t("dictionaries.config.entries.success.delete", "Dictionary entry deleted."), "success");
      } catch (err) {
        if (surfaceRecordConflict(err, t)) {
          return;
        }
        logger.error("Failed to delete dictionary entry", { err });
        flash(t("dictionaries.config.entries.error.delete", "Failed to delete dictionary entry."), "error");
      } finally {
        setIsDeleting(false);
      }
    },
    [confirm, dictionaryId, mutationContextId, queryClient, readOnly, readOnlyMessage, runMutation, retryLastMutation, t]
  );
  const tableContent = React.useMemo(() => {
    if (isInitialLoading) {
      return /* @__PURE__ */ jsx(TableRow, { children: /* @__PURE__ */ jsxs(TableCell, { colSpan: 4, className: "py-8 text-center text-sm text-muted-foreground", children: [
        /* @__PURE__ */ jsx(Spinner, { className: "mx-auto mb-2 h-5 w-5" }),
        t("dictionaries.config.entries.loading", "Loading entries\u2026")
      ] }) });
    }
    if (loadError) {
      return /* @__PURE__ */ jsx(TableRow, { children: /* @__PURE__ */ jsx(TableCell, { colSpan: 4, className: "py-6 text-center text-sm text-destructive", children: loadError }) });
    }
    if (!entries.length) {
      return /* @__PURE__ */ jsx(TableRow, { children: /* @__PURE__ */ jsx(TableCell, { colSpan: 4, className: "py-6 text-center text-sm text-muted-foreground", children: t("dictionaries.config.entries.empty", "No entries yet.") }) });
    }
    return entries.map((entry) => /* @__PURE__ */ jsxs(TableRow, { children: [
      /* @__PURE__ */ jsx(TableCell, { className: "font-medium", children: entry.value }),
      /* @__PURE__ */ jsx(TableCell, { children: entry.label }),
      /* @__PURE__ */ jsx(TableCell, { children: /* @__PURE__ */ jsx(
        DictionaryValue,
        {
          value: entry.value,
          map: dictionaryMap,
          fallback: /* @__PURE__ */ jsx("span", { className: "text-sm text-muted-foreground", children: t("dictionaries.config.entries.appearance.none", "None") })
        }
      ) }),
      /* @__PURE__ */ jsx(TableCell, { className: "flex items-center gap-2", children: readOnly ? /* @__PURE__ */ jsx("span", { className: "text-xs text-muted-foreground", children: t("dictionaries.config.entries.readOnlyActions", "Managed in parent organization") }) : /* @__PURE__ */ jsxs(Fragment, { children: [
        /* @__PURE__ */ jsx(
          Button,
          {
            type: "button",
            variant: "ghost",
            size: "icon",
            onClick: () => openDialog(entry),
            children: /* @__PURE__ */ jsx(Pencil, { className: "h-4 w-4" })
          }
        ),
        /* @__PURE__ */ jsx(
          Button,
          {
            type: "button",
            variant: "ghost",
            size: "icon",
            onClick: () => setTranslateEntry(entry),
            title: t("dictionaries.config.entries.actions.translate", "Translate"),
            children: /* @__PURE__ */ jsx(Languages, { className: "h-4 w-4" })
          }
        ),
        /* @__PURE__ */ jsx(
          Button,
          {
            type: "button",
            variant: "ghost",
            size: "icon",
            onClick: () => handleDelete(entry),
            disabled: isDeleting,
            children: /* @__PURE__ */ jsx(Trash2, { className: "h-4 w-4" })
          }
        )
      ] }) })
    ] }, entry.id));
  }, [dictionaryMap, entries, handleDelete, isDeleting, isInitialLoading, loadError, openDialog, readOnly, t]);
  return /* @__PURE__ */ jsxs("div", { className: "space-y-4", children: [
    /* @__PURE__ */ jsxs("div", { className: "flex flex-wrap items-center justify-between gap-3", children: [
      /* @__PURE__ */ jsxs("div", { children: [
        /* @__PURE__ */ jsx("h2", { className: "text-lg font-semibold", children: dictionaryName }),
        /* @__PURE__ */ jsx("p", { className: "text-sm text-muted-foreground", children: readOnly ? readOnlyMessage : t("dictionaries.config.entries.subtitle", "Manage reusable values and appearance for this dictionary.") })
      ] }),
      /* @__PURE__ */ jsxs("div", { className: "flex gap-2", children: [
        /* @__PURE__ */ jsxs(
          Button,
          {
            type: "button",
            variant: "outline",
            size: "sm",
            onClick: () => {
              dictionaryQuery.refetch().catch(() => {
              });
            },
            children: [
              /* @__PURE__ */ jsx(RefreshCw, { className: "mr-2 h-4 w-4" }),
              t("dictionaries.config.entries.actions.refresh", "Refresh")
            ]
          }
        ),
        /* @__PURE__ */ jsxs(
          Button,
          {
            type: "button",
            size: "sm",
            onClick: () => openDialog(),
            disabled: readOnly,
            title: readOnly ? readOnlyMessage : void 0,
            children: [
              /* @__PURE__ */ jsx(Plus, { className: "mr-2 h-4 w-4" }),
              t("dictionaries.config.entries.actions.add", "Add entry")
            ]
          }
        )
      ] })
    ] }),
    /* @__PURE__ */ jsx("div", { className: "overflow-hidden rounded-md border", children: /* @__PURE__ */ jsxs(Table, { children: [
      /* @__PURE__ */ jsx(TableHeader, { children: /* @__PURE__ */ jsxs(TableRow, { children: [
        /* @__PURE__ */ jsx(TableHead, { className: "w-48", children: t("dictionaries.config.entries.columns.value", "Value") }),
        /* @__PURE__ */ jsx(TableHead, { className: "w-48", children: t("dictionaries.config.entries.columns.label", "Label") }),
        /* @__PURE__ */ jsx(TableHead, { children: t("dictionaries.config.entries.columns.appearance", "Appearance") }),
        /* @__PURE__ */ jsx(TableHead, { className: "w-32 text-right", children: t("dictionaries.config.entries.columns.actions", "Actions") })
      ] }) }),
      /* @__PURE__ */ jsx(TableBody, { children: tableContent })
    ] }) }),
    /* @__PURE__ */ jsx(Dialog, { open: dialogOpen, onOpenChange: (open) => !open ? closeDialog() : void 0, children: /* @__PURE__ */ jsxs(DialogContent, { children: [
      /* @__PURE__ */ jsx(DialogHeader, { children: /* @__PURE__ */ jsx(DialogTitle, { children: formState.id ? t("dictionaries.config.entries.dialog.editTitle", "Edit dictionary entry") : t("dictionaries.config.entries.dialog.addTitle", "Add dictionary entry") }) }),
      /* @__PURE__ */ jsxs("div", { className: "space-y-4", children: [
        /* @__PURE__ */ jsxs("div", { className: "space-y-2", children: [
          /* @__PURE__ */ jsxs("label", { className: "text-sm font-medium", children: [
            t("dictionaries.config.entries.dialog.valueLabel", "Value"),
            /* @__PURE__ */ jsx("span", { className: "ml-1 text-destructive", children: "*" })
          ] }),
          /* @__PURE__ */ jsx(
            Input,
            {
              type: "text",
              value: formState.value,
              onChange: (event) => {
                const nextValue = event.target.value;
                setFormState((prev) => ({ ...prev, value: nextValue }));
                if (errors.value) {
                  setErrors((prev) => ({ ...prev, value: void 0 }));
                }
              },
              "aria-invalid": errors.value ? "true" : "false",
              "aria-describedby": "dictionary-entry-value-error"
            }
          ),
          errors.value ? /* @__PURE__ */ jsx("p", { id: "dictionary-entry-value-error", className: "text-xs text-destructive", children: errors.value }) : null
        ] }),
        /* @__PURE__ */ jsxs("div", { className: "space-y-2", children: [
          /* @__PURE__ */ jsx("label", { className: "text-sm font-medium", children: t("dictionaries.config.entries.dialog.labelLabel", "Label") }),
          /* @__PURE__ */ jsx(
            Input,
            {
              type: "text",
              value: formState.label,
              onChange: (event) => setFormState((prev) => ({ ...prev, label: event.target.value })),
              placeholder: t("dictionaries.config.entries.dialog.labelPlaceholder", "Display name shown in UI")
            }
          )
        ] }),
        /* @__PURE__ */ jsx(
          AppearanceSelector,
          {
            icon: appearance.icon,
            color: appearance.color,
            previewLabel: formState.label.trim() || formState.value.trim(),
            onIconChange: (next) => {
              appearance.setIcon(next);
              setFormState((prev) => ({ ...prev, icon: next }));
            },
            onColorChange: (next) => {
              appearance.setColor(next);
              setFormState((prev) => ({ ...prev, color: next }));
            },
            labels: {
              colorLabel: t("dictionaries.config.entries.dialog.colorLabel", "Color"),
              colorHelp: t("dictionaries.config.entries.dialog.colorHelp", "Pick a highlight color for this entry."),
              colorClearLabel: t("dictionaries.config.entries.dialog.colorClear", "Remove color"),
              iconLabel: t("dictionaries.config.entries.dialog.iconLabel", "Icon or emoji"),
              iconPlaceholder: t("dictionaries.config.entries.dialog.iconPlaceholder", "Type an emoji or icon token."),
              iconPickerTriggerLabel: t("dictionaries.config.entries.dialog.iconBrowse", "Browse icons and emoji"),
              iconSearchPlaceholder: t("dictionaries.config.entries.dialog.iconSearchPlaceholder", "Search icons or emojis\u2026"),
              iconSearchEmptyLabel: t("dictionaries.config.entries.dialog.iconSearchEmpty", "No icons match your search."),
              iconSuggestionsLabel: t("dictionaries.config.entries.dialog.iconSuggestions", "Suggestions"),
              iconClearLabel: t("dictionaries.config.entries.dialog.iconClear", "Remove icon"),
              previewEmptyLabel: t("dictionaries.config.entries.dialog.previewEmpty", "No appearance selected")
            }
          }
        )
      ] }),
      /* @__PURE__ */ jsxs(DialogFooter, { children: [
        /* @__PURE__ */ jsx(
          Button,
          {
            type: "button",
            variant: "ghost",
            onClick: closeDialog,
            disabled: isSaving,
            children: t("dictionaries.config.entries.dialog.cancel", "Cancel")
          }
        ),
        /* @__PURE__ */ jsxs(
          Button,
          {
            type: "button",
            onClick: handleSave,
            disabled: isSaving,
            children: [
              isSaving ? /* @__PURE__ */ jsx(Spinner, { className: "mr-2 h-4 w-4" }) : null,
              t("dictionaries.config.entries.dialog.save", "Save")
            ]
          }
        )
      ] })
    ] }) }),
    /* @__PURE__ */ jsx(Dialog, { open: !!translateEntry, onOpenChange: (open) => {
      if (!open) setTranslateEntry(null);
    }, children: /* @__PURE__ */ jsxs(DialogContent, { className: "max-w-2xl max-h-[80vh] overflow-y-auto", children: [
      /* @__PURE__ */ jsxs(DialogHeader, { children: [
        /* @__PURE__ */ jsx(DialogTitle, { children: t("translations.manager.translateEntry", "Translate: {{label}}", { label: translateEntry?.label ?? "" }) }),
        /* @__PURE__ */ jsx(DialogDescription, { children: t("translations.manager.translateEntryDescription", "Manage translations for this dictionary entry.") })
      ] }),
      translateEntry?.id && /* @__PURE__ */ jsx(
        TranslationManager,
        {
          mode: "embedded",
          entityType: "dictionaries:dictionary_entry",
          recordId: translateEntry.id,
          baseValues: { label: translateEntry.label },
          translatableFields: ["label"]
        }
      )
    ] }) }),
    ConfirmDialogElement
  ] });
}
export {
  DictionaryEntriesEditor
};
//# sourceMappingURL=DictionaryEntriesEditor.js.map
