"use client";
import { jsx } from "react/jsx-runtime";
import * as React from "react";
import { useRouter, usePathname } from "next/navigation";
import { Page, PageBody } from "@open-mercato/ui/backend/Page";
import { LoadingMessage, ErrorMessage, RecordNotFoundState } from "@open-mercato/ui/backend/detail";
import { CrudForm } from "@open-mercato/ui/backend/CrudForm";
import { updateCrud } from "@open-mercato/ui/backend/utils/crud";
import { flash } from "@open-mercato/ui/backend/FlashMessages";
import { apiCall } from "@open-mercato/ui/backend/utils/apiCall";
import { buildRecordInjectionContext, useSetCurrentRecordInjectionContext } from "@open-mercato/ui/backend/injection/recordContext";
import { useT } from "@open-mercato/shared/lib/i18n/context";
import {
  loadCurrencyOptions,
  exchangeRateGroups,
  validateExchangeRateForm,
  buildExchangeRatePayload
} from "../../../lib/exchangeRateFormConfig.js";
function formatDateTimeLocal(date) {
  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, "0");
  const day = String(date.getDate()).padStart(2, "0");
  const hours = String(date.getHours()).padStart(2, "0");
  const minutes = String(date.getMinutes()).padStart(2, "0");
  return `${year}-${month}-${day}T${hours}:${minutes}`;
}
function EditExchangeRatePage({ params }) {
  const t = useT();
  const router = useRouter();
  const pathname = usePathname();
  const [exchangeRate, setExchangeRate] = React.useState(null);
  const [loading, setLoading] = React.useState(true);
  const [error, setError] = React.useState(null);
  const [isNotFound, setIsNotFound] = React.useState(false);
  const loadOptions = React.useCallback(
    (query) => loadCurrencyOptions(apiCall, query),
    []
  );
  React.useEffect(() => {
    async function loadExchangeRate() {
      try {
        const response = await apiCall(`/api/currencies/exchange-rates?id=${params?.id}`);
        if (response.ok && response.result && response.result.items.length > 0) {
          setExchangeRate(response.result.items[0]);
        } else if (response.ok) {
          setIsNotFound(true);
        } else {
          setError(t("exchangeRates.form.errors.load"));
        }
      } catch (err) {
        setError(t("exchangeRates.form.errors.load"));
      } finally {
        setLoading(false);
      }
    }
    loadExchangeRate();
  }, [params, t]);
  const groups = React.useMemo(
    () => exchangeRateGroups(t, loadOptions),
    [t, loadOptions]
  );
  useSetCurrentRecordInjectionContext(
    buildRecordInjectionContext({
      resourceKind: "currencies.exchange_rate",
      resourceId: exchangeRate?.id ?? null,
      updatedAt: exchangeRate?.updatedAt ?? exchangeRate?.updated_at ?? null,
      data: exchangeRate,
      path: pathname
    })
  );
  if (loading) {
    return /* @__PURE__ */ jsx(Page, { children: /* @__PURE__ */ jsx(PageBody, { children: /* @__PURE__ */ jsx(LoadingMessage, { label: t("exchangeRates.form.loading") }) }) });
  }
  if (isNotFound) {
    return /* @__PURE__ */ jsx(Page, { children: /* @__PURE__ */ jsx(PageBody, { children: /* @__PURE__ */ jsx(
      RecordNotFoundState,
      {
        label: t("exchangeRates.form.errors.notFound"),
        backHref: "/backend/exchange-rates",
        backLabel: t("exchangeRates.form.actions.backToList", "Back to exchange rates")
      }
    ) }) });
  }
  if (error || !exchangeRate) {
    return /* @__PURE__ */ jsx(Page, { children: /* @__PURE__ */ jsx(PageBody, { children: /* @__PURE__ */ jsx(ErrorMessage, { label: error ?? t("exchangeRates.form.errors.load") }) }) });
  }
  return /* @__PURE__ */ jsx(Page, { children: /* @__PURE__ */ jsx(PageBody, { children: /* @__PURE__ */ jsx(
    CrudForm,
    {
      title: t("exchangeRates.edit.title"),
      backHref: "/backend/exchange-rates",
      versionHistory: { resourceKind: "currencies.exchange_rate", resourceId: exchangeRate.id },
      fields: [],
      groups,
      optimisticLockUpdatedAt: exchangeRate.updatedAt ?? exchangeRate.updated_at ?? null,
      initialValues: {
        fromCurrencyCode: exchangeRate.fromCurrencyCode,
        toCurrencyCode: exchangeRate.toCurrencyCode,
        rate: parseFloat(exchangeRate.rate),
        date: formatDateTimeLocal(new Date(exchangeRate.date)),
        source: exchangeRate.source || "",
        type: exchangeRate.type || "",
        isActive: exchangeRate.isActive
      },
      submitLabel: t("exchangeRates.form.action.save"),
      cancelHref: "/backend/exchange-rates",
      onSubmit: async (values) => {
        const validated = validateExchangeRateForm(values, t);
        const payload = {
          id: exchangeRate.id,
          ...buildExchangeRatePayload(values, validated)
        };
        await updateCrud("currencies/exchange-rates", payload);
        flash(t("exchangeRates.flash.updated"), "success");
        router.push("/backend/exchange-rates");
      }
    }
  ) }) });
}
export {
  EditExchangeRatePage as default
};
//# sourceMappingURL=page.js.map
