"use client";
import { jsx } from "react/jsx-runtime";
import * as React from "react";
import { flash } from "@open-mercato/ui/backend/FlashMessages";
import { LoadingMessage } from "@open-mercato/ui/backend/detail";
import { createTranslatorWithFallback } from "@open-mercato/shared/lib/i18n/translate";
import { useT } from "@open-mercato/shared/lib/i18n/context";
import AddressTiles from "./AddressTiles.js";
import { ComponentReplacementHandles } from "@open-mercato/shared/modules/widgets/component-registry";
import { useRegisteredComponent } from "../injection/useRegisteredComponent.js";
function generateTempId() {
  if (typeof crypto !== "undefined" && typeof crypto.randomUUID === "function") return crypto.randomUUID();
  return `tmp_${Math.random().toString(36).slice(2)}`;
}
function AddressesSectionImpl({
  entityId,
  emptyLabel,
  addActionLabel,
  emptyState,
  onActionChange,
  translator,
  onLoadingChange,
  dataAdapter,
  dataContext,
  addressTypesAdapter,
  addressTypesContext,
  loadFormat,
  formatContext,
  labelPrefix = "customers.people.detail.addresses"
}) {
  const tHook = useT();
  const fallbackTranslator = React.useMemo(() => createTranslatorWithFallback(tHook), [tHook]);
  const t = translator ?? fallbackTranslator;
  const label = React.useCallback(
    (suffix, fallback, params) => t(`${labelPrefix}.${suffix}`, fallback, params),
    [labelPrefix, t]
  );
  const normalizedEntityId = React.useMemo(() => {
    if (typeof entityId !== "string") return null;
    const trimmed = entityId.trim();
    return trimmed.length ? trimmed : null;
  }, [entityId]);
  const [addresses, setAddresses] = React.useState([]);
  const [isSubmitting, setIsSubmitting] = React.useState(false);
  const [isLoading, setIsLoading] = React.useState(() => Boolean(normalizedEntityId));
  const loadingCounterRef = React.useRef(0);
  const pushLoading = React.useCallback(() => {
    loadingCounterRef.current += 1;
    if (loadingCounterRef.current === 1) {
      onLoadingChange?.(true);
    }
  }, [onLoadingChange]);
  const popLoading = React.useCallback(() => {
    loadingCounterRef.current = Math.max(0, loadingCounterRef.current - 1);
    if (loadingCounterRef.current === 0) {
      onLoadingChange?.(false);
    }
  }, [onLoadingChange]);
  const loadAddresses = React.useCallback(async () => {
    if (!normalizedEntityId) {
      setAddresses([]);
      setIsLoading(false);
      return;
    }
    setIsLoading(true);
    pushLoading();
    try {
      const items = await dataAdapter.list({ entityId: normalizedEntityId, context: dataContext });
      setAddresses(items);
    } catch (err) {
      const message = err instanceof Error && err.message ? err.message : label("error", "Failed to load addresses.");
      flash(message, "error");
      setAddresses([]);
    } finally {
      setIsLoading(false);
      popLoading();
    }
  }, [dataAdapter, dataContext, label, normalizedEntityId, popLoading, pushLoading]);
  React.useEffect(() => {
    void loadAddresses();
  }, [loadAddresses]);
  const handleCreate = React.useCallback(
    async (payload) => {
      if (!normalizedEntityId) {
        throw new Error(label("error", "Failed to save address."));
      }
      pushLoading();
      setIsSubmitting(true);
      try {
        const response = await dataAdapter.create({
          entityId: normalizedEntityId,
          payload,
          context: dataContext
        });
        const newAddress = {
          id: typeof response === "object" && response && typeof response.id === "string" ? response.id : generateTempId(),
          name: payload.name ?? null,
          purpose: payload.purpose ?? null,
          companyName: payload.companyName ?? null,
          addressLine1: payload.addressLine1,
          addressLine2: payload.addressLine2 ?? null,
          buildingNumber: payload.buildingNumber ?? null,
          flatNumber: payload.flatNumber ?? null,
          city: payload.city ?? null,
          region: payload.region ?? null,
          postalCode: payload.postalCode ?? null,
          country: payload.country ? payload.country.toUpperCase() : null,
          isPrimary: payload.isPrimary ?? false
        };
        setAddresses((prev) => {
          const existing = payload.isPrimary ? prev.map((addr) => ({ ...addr, isPrimary: false })) : prev;
          return [newAddress, ...existing];
        });
        flash(label("success", "Address saved."), "success");
      } catch (err) {
        const message = err instanceof Error && err.message ? err.message : label("error", "Failed to save address.");
        const error = new Error(message);
        if (err && typeof err === "object" && err.details) {
          error.details = err.details;
        }
        throw error;
      } finally {
        setIsSubmitting(false);
        popLoading();
      }
    },
    [dataAdapter, dataContext, label, normalizedEntityId, popLoading, pushLoading]
  );
  const handleUpdate = React.useCallback(
    async (id, payload) => {
      if (!normalizedEntityId) {
        throw new Error(label("error", "Failed to save address."));
      }
      pushLoading();
      setIsSubmitting(true);
      try {
        await dataAdapter.update({ id, payload, context: dataContext });
        setAddresses((prev) => {
          return prev.map((address) => {
            if (address.id !== id) {
              return payload.isPrimary ? { ...address, isPrimary: false } : address;
            }
            return {
              ...address,
              name: payload.name ?? null,
              purpose: payload.purpose ?? null,
              companyName: payload.companyName ?? null,
              addressLine1: payload.addressLine1,
              addressLine2: payload.addressLine2 ?? null,
              buildingNumber: payload.buildingNumber ?? null,
              flatNumber: payload.flatNumber ?? null,
              city: payload.city ?? null,
              region: payload.region ?? null,
              postalCode: payload.postalCode ?? null,
              country: payload.country ? payload.country.toUpperCase() : null,
              isPrimary: payload.isPrimary ?? false
            };
          });
        });
        flash(label("success", "Address saved."), "success");
      } catch (err) {
        const message = err instanceof Error && err.message ? err.message : label("error", "Failed to save address.");
        const error = new Error(message);
        if (err && typeof err === "object" && err.details) {
          error.details = err.details;
        }
        throw error;
      } finally {
        setIsSubmitting(false);
        popLoading();
      }
    },
    [dataAdapter, dataContext, label, normalizedEntityId, popLoading, pushLoading]
  );
  const handleDelete = React.useCallback(
    async (id) => {
      if (!normalizedEntityId) {
        throw new Error(label("error", "Failed to delete address."));
      }
      pushLoading();
      setIsSubmitting(true);
      try {
        await dataAdapter.delete({ id, context: dataContext });
        setAddresses((prev) => prev.filter((address) => address.id !== id));
        flash(label("deleted", "Address deleted."), "success");
      } catch (err) {
        const message = err instanceof Error && err.message ? err.message : label("error", "Failed to delete address.");
        flash(message, "error");
        throw err;
      } finally {
        setIsSubmitting(false);
        popLoading();
      }
    },
    [dataAdapter, dataContext, label, normalizedEntityId, popLoading, pushLoading]
  );
  const displayAddresses = React.useMemo(() => {
    return addresses.map((address) => ({
      id: address.id,
      name: address.name ?? void 0,
      purpose: address.purpose ?? void 0,
      companyName: address.companyName ?? void 0,
      addressLine1: address.addressLine1,
      addressLine2: address.addressLine2 ?? void 0,
      buildingNumber: address.buildingNumber ?? void 0,
      flatNumber: address.flatNumber ?? void 0,
      city: address.city ?? void 0,
      region: address.region ?? void 0,
      postalCode: address.postalCode ?? void 0,
      country: address.country ?? void 0,
      isPrimary: address.isPrimary ?? false
    }));
  }, [addresses]);
  const [addAction, setAddAction] = React.useState(null);
  const handleAddActionChange = React.useCallback(
    (action) => {
      setAddAction(action);
    },
    []
  );
  React.useEffect(() => {
    if (!onActionChange) return;
    if (!addAction || addresses.length === 0) {
      onActionChange(null);
      return;
    }
    onActionChange({
      label: addActionLabel,
      onClick: addAction.openCreateForm,
      disabled: addAction.addDisabled
    });
  }, [addAction, addActionLabel, addresses.length, onActionChange]);
  return /* @__PURE__ */ jsx("div", { className: "mt-4", children: isLoading ? /* @__PURE__ */ jsx("div", { className: "flex justify-center", children: /* @__PURE__ */ jsx(
    LoadingMessage,
    {
      label: label("loading", "Loading addresses\u2026"),
      className: "min-h-[120px] w-full justify-center border-0 bg-transparent p-0"
    }
  ) }) : /* @__PURE__ */ jsx(
    AddressTiles,
    {
      addresses: displayAddresses,
      onCreate: handleCreate,
      onUpdate: handleUpdate,
      onDelete: handleDelete,
      isSubmitting,
      emptyLabel,
      t,
      hideAddButton: true,
      onAddActionChange: handleAddActionChange,
      emptyStateTitle: emptyState.title,
      emptyStateActionLabel: emptyState.actionLabel,
      labelPrefix,
      addressTypesAdapter,
      addressTypesContext,
      loadFormat,
      formatContext
    }
  ) });
}
function AddressesSection(props) {
  const handle = ComponentReplacementHandles.section("ui.detail", "AddressesSection");
  const Resolved = useRegisteredComponent(
    handle,
    AddressesSectionImpl
  );
  return /* @__PURE__ */ jsx("div", { "data-component-handle": handle, children: /* @__PURE__ */ jsx(Resolved, { ...props }) });
}
var AddressesSection_default = AddressesSection;
export {
  AddressesSection,
  AddressesSection_default as default
};
//# sourceMappingURL=AddressesSection.js.map
