"use client";
import { jsx, jsxs } from "react/jsx-runtime";
import * as React from "react";
import { z } from "zod";
import { DataTable } from "@open-mercato/ui/backend/DataTable";
import { RowActions } from "@open-mercato/ui/backend/RowActions";
import { Button } from "@open-mercato/ui/primitives/button";
import {
  Dialog,
  DialogContent,
  DialogHeader,
  DialogTitle
} from "@open-mercato/ui/primitives/dialog";
import { Label } from "@open-mercato/ui/primitives/label";
import { CrudForm } from "@open-mercato/ui/backend/CrudForm";
import { flash } from "@open-mercato/ui/backend/FlashMessages";
import { apiCall, readApiResultOrThrow, 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 { raiseCrudError } from "@open-mercato/ui/backend/utils/serverErrors";
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 {
  listPaymentProviders
} from "../lib/providers/index.js";
import { isRecord } from "@open-mercato/shared/lib/utils";
import { renderProviderFieldInput } from "./ProviderFieldInput.js";
import { createLogger } from "@open-mercato/shared/lib/logger";
const logger = createLogger("sales");
const paymentFormSchema = z.object({
  name: z.string().trim().min(1),
  code: z.string().trim().min(1),
  providerKey: z.string().trim().optional(),
  description: z.string().optional(),
  terms: z.string().optional(),
  isActive: z.boolean().optional(),
  providerSettings: z.record(z.string(), z.unknown()).optional()
});
const DEFAULT_FORM = {
  name: "",
  code: "",
  providerKey: "",
  description: "",
  terms: "",
  isActive: true,
  providerSettings: {}
};
function createPaymentProviderSettingsRenderer(params) {
  const { providers, selectPrompt, noFieldsLabel } = params;
  return function PaymentProviderSettingsField({
    value,
    setValue,
    values
  }) {
    const providerKey = values && typeof values.providerKey === "string" && values.providerKey.trim().length ? values.providerKey : null;
    const provider = providers.find((entry) => entry.key === providerKey);
    const previousKey = React.useRef(providerKey);
    React.useEffect(() => {
      if (providerKey !== previousKey.current) {
        const defaults = provider?.settings?.defaults ?? null;
        setValue(defaults && typeof defaults === "object" ? defaults : {});
        previousKey.current = providerKey;
      }
    }, [providerKey, provider, setValue]);
    if (!provider) {
      return /* @__PURE__ */ jsx("p", { className: "text-sm text-muted-foreground", children: selectPrompt });
    }
    const settings = isRecord(value) ? value : {};
    const fields = provider.settings?.fields ?? [];
    if (!fields.length) {
      return /* @__PURE__ */ jsx("p", { className: "text-sm text-muted-foreground", children: noFieldsLabel });
    }
    return /* @__PURE__ */ jsx("div", { className: "space-y-4", children: fields.map((field) => {
      const fieldValue = settings[field.key];
      return /* @__PURE__ */ jsxs("div", { className: "space-y-1.5", children: [
        /* @__PURE__ */ jsxs(Label, { htmlFor: field.key, className: "text-sm font-medium", children: [
          field.label,
          field.required ? " *" : ""
        ] }),
        field.description ? /* @__PURE__ */ jsx("p", { className: "text-xs text-muted-foreground", children: field.description }) : null,
        renderProviderFieldInput({
          field,
          value: fieldValue,
          onChange: (next) => setValue({ ...settings, [field.key]: next })
        })
      ] }, field.key);
    }) });
  };
}
function PaymentMethodsSettings() {
  const t = useT();
  const scopeVersion = useOrganizationScopeVersion();
  const { confirm, ConfirmDialogElement } = useConfirmDialog();
  const providers = React.useMemo(() => listPaymentProviders(), []);
  const providerOptions = React.useMemo(
    () => providers.map((provider) => ({ value: provider.key, label: provider.label })),
    [providers]
  );
  const ProviderSettingsField = React.useMemo(
    () => createPaymentProviderSettingsRenderer({
      providers,
      selectPrompt: t(
        "sales.config.paymentMethods.form.selectProvider",
        "Choose a provider to configure settings."
      ),
      noFieldsLabel: t("sales.config.paymentMethods.form.noSettings", "No configurable settings.")
    }),
    [providers, t]
  );
  const translations = React.useMemo(() => ({
    title: t("sales.config.paymentMethods.title", "Payment methods"),
    description: t(
      "sales.config.paymentMethods.description",
      "Configure payment providers and any checkout fees."
    ),
    actions: {
      add: t("sales.config.paymentMethods.actions.add", "Add payment method"),
      edit: t("sales.config.paymentMethods.actions.edit", "Edit"),
      delete: t("sales.config.paymentMethods.actions.delete", "Delete"),
      deleteConfirm: t("sales.config.paymentMethods.actions.deleteConfirm", 'Delete "{{name}}"?'),
      refresh: t("sales.config.paymentMethods.actions.refresh", "Refresh")
    },
    table: {
      name: t("sales.config.paymentMethods.table.name", "Name"),
      code: t("sales.config.paymentMethods.table.code", "Code"),
      provider: t("sales.config.paymentMethods.table.provider", "Provider"),
      active: t("sales.config.paymentMethods.table.active", "Active"),
      statusActive: t("sales.config.paymentMethods.table.statusActive", "Active"),
      statusInactive: t("sales.config.paymentMethods.table.statusInactive", "Inactive"),
      updatedAt: t("sales.config.paymentMethods.table.updatedAt", "Updated"),
      empty: t("sales.config.paymentMethods.table.empty", "No payment methods yet."),
      search: t("sales.config.paymentMethods.table.search", "Search payment methods\u2026")
    },
    form: {
      createTitle: t("sales.config.paymentMethods.form.createTitle", "Add payment method"),
      editTitle: t("sales.config.paymentMethods.form.editTitle", "Edit payment method"),
      name: t("sales.config.paymentMethods.form.name", "Name"),
      code: t("sales.config.paymentMethods.form.code", "Code"),
      provider: t("sales.config.paymentMethods.form.provider", "Provider"),
      description: t("sales.config.paymentMethods.form.description", "Description"),
      terms: t("sales.config.paymentMethods.form.terms", "Terms"),
      isActive: t("sales.config.paymentMethods.form.isActive", "Active"),
      providerSettings: t("sales.config.paymentMethods.form.providerSettings", "Provider settings"),
      save: t("sales.config.paymentMethods.form.save", "Save"),
      cancel: t("sales.config.paymentMethods.form.cancel", "Cancel")
    },
    messages: {
      saved: t("sales.config.paymentMethods.messages.saved", "Payment method saved."),
      deleted: t("sales.config.paymentMethods.messages.deleted", "Payment method deleted.")
    },
    errors: {
      load: t("sales.config.paymentMethods.errors.load", "Failed to load payment methods."),
      save: t("sales.config.paymentMethods.errors.save", "Failed to save payment method."),
      delete: t("sales.config.paymentMethods.errors.delete", "Failed to delete payment method.")
    }
  }), [t]);
  const [entries, setEntries] = React.useState([]);
  const [loading, setLoading] = React.useState(false);
  const [dialog, setDialog] = React.useState(null);
  const [formValues, setFormValues] = React.useState(DEFAULT_FORM);
  const [search, setSearch] = React.useState("");
  const [submitting, setSubmitting] = React.useState(false);
  const loadEntries = React.useCallback(async () => {
    setLoading(true);
    try {
      const payload = await readApiResultOrThrow(
        "/api/sales/payment-methods?pageSize=100",
        void 0,
        { errorMessage: translations.errors.load, fallback: { items: [] } }
      );
      const items = Array.isArray(payload.items) ? payload.items : [];
      setEntries(
        items.map((item) => {
          const providerKey = typeof item.providerKey === "string" ? item.providerKey : typeof item.provider_key === "string" ? item.provider_key : null;
          const provider = providers.find((entry) => entry.key === providerKey);
          return {
            id: String(item.id ?? ""),
            name: typeof item.name === "string" && item.name.length ? item.name : "\u2014",
            code: typeof item.code === "string" ? item.code : "",
            providerKey,
            providerLabel: provider?.label ?? null,
            description: typeof item.description === "string" ? item.description : null,
            terms: typeof item.terms === "string" ? item.terms : null,
            isActive: typeof item.isActive === "boolean" ? item.isActive : typeof item?.is_active === "boolean" ? item.is_active : false,
            updatedAt: typeof item.updatedAt === "string" ? item.updatedAt : null,
            providerSettings: item && typeof item.providerSettings === "object" ? item.providerSettings : null
          };
        })
      );
    } catch (err) {
      logger.error("sales.payment-methods.list failed", { err });
      flash(translations.errors.load, "error");
    } finally {
      setLoading(false);
    }
  }, [providers, translations.errors.load]);
  React.useEffect(() => {
    void loadEntries();
  }, [loadEntries, scopeVersion]);
  const openCreate = React.useCallback(() => {
    const defaultProvider = providerOptions[0]?.value ?? "";
    setFormValues({
      ...DEFAULT_FORM,
      providerKey: defaultProvider,
      providerSettings: {}
    });
    setDialog({ mode: "create" });
  }, [providerOptions]);
  const openEdit = React.useCallback((entry) => {
    setFormValues({
      name: entry.name,
      code: entry.code,
      providerKey: entry.providerKey ?? "",
      description: entry.description ?? "",
      terms: entry.terms ?? "",
      isActive: entry.isActive,
      providerSettings: entry.providerSettings ?? {}
    });
    setDialog({ mode: "edit", entry });
  }, []);
  const closeDialog = React.useCallback(() => {
    setDialog(null);
  }, []);
  const deleteEntry = React.useCallback(async (entry) => {
    const message = translations.actions.deleteConfirm.replace("{{name}}", entry.name);
    const confirmed = await confirm({
      title: message,
      variant: "destructive"
    });
    if (!confirmed) return;
    try {
      const headers = buildOptimisticLockHeader(entry.updatedAt);
      const call = await withScopedApiRequestHeaders(headers, () => apiCall("/api/sales/payment-methods", {
        method: "DELETE",
        headers: { "content-type": "application/json" },
        body: JSON.stringify({ id: entry.id })
      }));
      if (!call.ok) {
        if (surfaceRecordConflict({ status: call.status, body: call.result }, t)) return;
        await raiseCrudError(call.response, translations.errors.delete);
      }
      flash(translations.messages.deleted, "success");
      await loadEntries();
    } catch (err) {
      logger.error("sales.payment-methods.delete failed", { err });
      const message2 = err instanceof Error ? err.message : translations.errors.delete;
      flash(message2, "error");
    }
  }, [confirm, loadEntries, translations.actions.deleteConfirm, translations.errors.delete, translations.messages.deleted]);
  const handleSubmit = React.useCallback(async (values) => {
    if (!dialog) return;
    setSubmitting(true);
    const payload = {
      name: values.name.trim(),
      code: values.code.trim().toLowerCase(),
      description: values.description?.trim() || void 0,
      providerKey: values.providerKey?.trim() || void 0,
      terms: values.terms?.trim() || void 0,
      isActive: values.isActive ?? true,
      providerSettings: isRecord(values.providerSettings) ? values.providerSettings : void 0
    };
    const path = "/api/sales/payment-methods";
    const method = dialog.mode === "create" ? "POST" : "PUT";
    if (dialog.mode === "edit") payload.id = dialog.entry.id;
    try {
      const savePaymentMethod = () => apiCall(path, {
        method,
        headers: { "content-type": "application/json" },
        body: JSON.stringify(payload)
      });
      const headers = buildOptimisticLockHeader(dialog.mode === "edit" ? dialog.entry.updatedAt : null);
      const call = await withScopedApiRequestHeaders(headers, savePaymentMethod);
      if (!call.ok) {
        if (surfaceRecordConflict({ status: call.status, body: call.result }, t)) return;
        await raiseCrudError(call.response, translations.errors.save);
      }
      flash(translations.messages.saved, "success");
      await loadEntries();
      closeDialog();
    } catch (err) {
      logger.error("sales.payment-methods.save failed", { err });
      const message = err instanceof Error ? err.message : translations.errors.save;
      flash(message, "error");
    } finally {
      setSubmitting(false);
    }
  }, [closeDialog, dialog, loadEntries, translations.errors.save, translations.messages.saved]);
  const fields = React.useMemo(() => [
    { id: "name", label: translations.form.name, type: "text", required: true },
    { id: "code", label: translations.form.code, type: "text", required: true },
    {
      id: "providerKey",
      label: translations.form.provider,
      type: "select",
      required: false,
      options: providerOptions
    },
    { id: "description", label: translations.form.description, type: "textarea" },
    { id: "terms", label: translations.form.terms, type: "textarea" },
    { id: "isActive", label: translations.form.isActive, type: "checkbox" },
    {
      id: "providerSettings",
      label: translations.form.providerSettings,
      type: "custom",
      component: ProviderSettingsField
    }
  ], [ProviderSettingsField, providerOptions, translations.form.code, translations.form.description, translations.form.isActive, translations.form.name, translations.form.provider, translations.form.providerSettings, translations.form.terms]);
  const columns = React.useMemo(() => [
    {
      accessorKey: "name",
      header: translations.table.name,
      cell: ({ row }) => /* @__PURE__ */ jsxs("div", { className: "flex flex-col", children: [
        /* @__PURE__ */ jsx("span", { className: "font-medium", children: row.original.name }),
        /* @__PURE__ */ jsx("span", { className: "text-xs text-muted-foreground", children: row.original.code })
      ] })
    },
    {
      accessorKey: "providerKey",
      header: translations.table.provider,
      cell: ({ row }) => /* @__PURE__ */ jsx("span", { className: "text-sm", children: row.original.providerLabel ?? row.original.providerKey ?? "\u2014" })
    },
    {
      accessorKey: "isActive",
      header: translations.table.active,
      cell: ({ row }) => /* @__PURE__ */ jsx("span", { className: "text-sm", children: row.original.isActive ? translations.table.statusActive : translations.table.statusInactive })
    },
    {
      accessorKey: "updatedAt",
      header: translations.table.updatedAt,
      cell: ({ row }) => /* @__PURE__ */ jsx("span", { className: "text-xs text-muted-foreground", children: row.original.updatedAt ? new Date(row.original.updatedAt).toLocaleString() : "\u2014" })
    }
  ], [translations]);
  const filteredEntries = React.useMemo(() => {
    if (!search.trim()) return entries;
    const term = search.trim().toLowerCase();
    return entries.filter(
      (entry) => entry.name.toLowerCase().includes(term) || entry.code.toLowerCase().includes(term) || (entry.providerLabel ?? "").toLowerCase().includes(term) || (entry.providerKey ?? "").toLowerCase().includes(term)
    );
  }, [entries, search]);
  return /* @__PURE__ */ jsxs("section", { className: "rounded border bg-card text-card-foreground shadow-sm", children: [
    /* @__PURE__ */ jsxs("div", { className: "border-b px-6 py-4 space-y-1", children: [
      /* @__PURE__ */ jsx("h2", { className: "text-lg font-medium", children: translations.title }),
      /* @__PURE__ */ jsx("p", { className: "text-sm text-muted-foreground", children: translations.description })
    ] }),
    /* @__PURE__ */ jsx("div", { className: "px-2 py-4 sm:px-4", children: /* @__PURE__ */ jsx(
      DataTable,
      {
        embedded: true,
        isLoading: loading,
        columns,
        data: filteredEntries,
        searchValue: search,
        onSearchChange: setSearch,
        searchPlaceholder: translations.table.search,
        emptyState: /* @__PURE__ */ jsx("p", { className: "py-8 text-center text-sm text-muted-foreground", children: translations.table.empty }),
        actions: /* @__PURE__ */ jsx(Button, { size: "sm", onClick: openCreate, children: translations.actions.add }),
        refreshButton: {
          label: translations.actions.refresh,
          onRefresh: () => {
            void loadEntries();
          },
          isRefreshing: loading
        },
        rowActions: (row) => /* @__PURE__ */ jsx(
          RowActions,
          {
            items: [
              { id: "edit", label: translations.actions.edit, onSelect: () => openEdit(row) },
              { id: "delete", label: translations.actions.delete, destructive: true, onSelect: () => deleteEntry(row) }
            ]
          }
        )
      }
    ) }),
    /* @__PURE__ */ jsx(Dialog, { open: dialog !== null, onOpenChange: (next) => !next && closeDialog(), children: /* @__PURE__ */ jsxs(DialogContent, { className: "max-w-3xl", children: [
      /* @__PURE__ */ jsx(DialogHeader, { children: /* @__PURE__ */ jsx(DialogTitle, { children: dialog?.mode === "edit" ? translations.form.editTitle : translations.form.createTitle }) }),
      /* @__PURE__ */ jsx(
        CrudForm,
        {
          schema: paymentFormSchema,
          fields,
          initialValues: formValues,
          optimisticLockUpdatedAt: dialog?.mode === "edit" ? dialog.entry.updatedAt : null,
          submitLabel: translations.form.save,
          onSubmit: handleSubmit,
          cancelHref: void 0,
          embedded: true,
          isLoading: submitting,
          twoColumn: true,
          extraActions: /* @__PURE__ */ jsx(Button, { type: "button", variant: "ghost", onClick: closeDialog, children: translations.form.cancel })
        }
      )
    ] }) }),
    ConfirmDialogElement
  ] });
}
export {
  PaymentMethodsSettings
};
//# sourceMappingURL=PaymentMethodsSettings.js.map
