"use client";
import { Fragment, jsx, jsxs } from "react/jsx-runtime";
import * as React from "react";
import { Loader2, Pencil, Plus, Trash2, X } from "lucide-react";
import { Button } from "@open-mercato/ui/primitives/button";
import { flash } from "@open-mercato/ui/backend/FlashMessages";
import { TabEmptyState } from "@open-mercato/ui/backend/detail";
import { useOrganizationScopeVersion } from "@open-mercato/shared/lib/frontend/useOrganizationScope";
import { AddressView, formatAddressString } from "./addressFormat.js";
import AddressEditor from "./AddressEditor.js";
const defaultDraft = {
  name: "",
  purpose: "",
  companyName: "",
  addressLine1: "",
  addressLine2: "",
  buildingNumber: "",
  flatNumber: "",
  city: "",
  region: "",
  postalCode: "",
  country: "",
  isPrimary: false
};
const serverFieldMap = {
  name: "name",
  purpose: "purpose",
  companyName: "companyName",
  addressLine1: "addressLine1",
  addressLine2: "addressLine2",
  buildingNumber: "buildingNumber",
  flatNumber: "flatNumber",
  city: "city",
  region: "region",
  postalCode: "postalCode",
  country: "country",
  isPrimary: "isPrimary"
};
function normalizeOptional(value) {
  const trimmed = value.trim();
  return trimmed.length ? trimmed : void 0;
}
function extractValidationDetails(error) {
  if (!error || typeof error !== "object") return [];
  const candidate = error.details;
  if (!Array.isArray(candidate)) return [];
  return candidate.map((entry) => entry && typeof entry === "object" ? entry : null).filter((entry) => entry !== null);
}
function resolveFieldMessage(detail, fieldLabel, t, prefix) {
  const label = (suffix, fallback) => t(`${prefix}.${suffix}`, fallback);
  switch (detail.code) {
    case "invalid_type":
      return label("validation.invalid", "Invalid value for {{field}}").replace("{{field}}", fieldLabel);
    case "too_small":
      if (detail.minimum === 1 && detail.type === "string") {
        return label("validation.required", "{{field}} is required").replace("{{field}}", fieldLabel);
      }
      return label("validation.generic", "Invalid value for {{field}}").replace("{{field}}", fieldLabel);
    case "too_big":
      if (typeof detail.maximum === "number") {
        return label("validation.tooLong", "{{field}} is too long").replace("{{field}}", fieldLabel).replace("{{max}}", `${detail.maximum}`);
      }
      return label("validation.generic", "Invalid value for {{field}}").replace("{{field}}", fieldLabel);
    default:
      return label("validation.generic", "Invalid value for {{field}}").replace("{{field}}", fieldLabel);
  }
}
function AddressTiles({
  addresses,
  onCreate,
  onUpdate,
  onDelete,
  t,
  emptyLabel,
  isSubmitting = false,
  gridClassName = "grid grid-cols-1 gap-2 sm:gap-4 sm:grid-cols-2 lg:grid-cols-3 2xl:grid-cols-4",
  hideAddButton = false,
  onAddActionChange,
  emptyStateTitle,
  emptyStateActionLabel,
  labelPrefix = "customers.people.detail.addresses",
  addressTypesAdapter,
  addressTypesContext,
  loadFormat,
  formatContext
}) {
  const scopeVersion = useOrganizationScopeVersion();
  const [isFormOpen, setIsFormOpen] = React.useState(false);
  const [editingId, setEditingId] = React.useState(null);
  const [draft, setDraft] = React.useState(defaultDraft);
  const [saving, setSaving] = React.useState(false);
  const [deletingId, setDeletingId] = React.useState(null);
  const [generalError, setGeneralError] = React.useState(null);
  const [fieldErrors, setFieldErrors] = React.useState({});
  const [format, setFormat] = React.useState("line_first");
  const [formatLoading, setFormatLoading] = React.useState(false);
  const label = React.useCallback(
    (suffix, fallback, params) => t(`${labelPrefix}.${suffix}`, fallback, params),
    [labelPrefix, t]
  );
  const fieldLabels = React.useMemo(
    () => ({
      name: label("fields.label", "Label"),
      purpose: label("fields.type", "Address type"),
      companyName: label("fields.companyName", "Company name"),
      addressLine1: label("fields.line1", "Address line 1"),
      addressLine2: label("fields.line2", "Address line 2"),
      street: label("fields.street", "Street"),
      buildingNumber: label("fields.buildingNumber", "Building number"),
      flatNumber: label("fields.flatNumber", "Flat number"),
      city: label("fields.city", "City"),
      region: label("fields.region", "Region"),
      postalCode: label("fields.postalCode", "Postal code"),
      country: label("fields.country", "Country"),
      isPrimary: label("fields.primary", "Primary address")
    }),
    [label]
  );
  const line1FieldLabel = React.useMemo(
    () => format === "street_first" ? fieldLabels.street : fieldLabels.addressLine1,
    [fieldLabels.addressLine1, fieldLabels.street, format]
  );
  const resetForm = React.useCallback(() => {
    setDraft(defaultDraft);
    setFieldErrors({});
    setGeneralError(null);
    setEditingId(null);
  }, []);
  React.useEffect(() => {
    let cancelled = false;
    async function loadFormatValue() {
      if (!loadFormat) {
        setFormat("line_first");
        setFormatLoading(false);
        return;
      }
      setFormatLoading(true);
      try {
        const value = await loadFormat(formatContext);
        if (!cancelled && (value === "street_first" || value === "line_first")) {
          setFormat(value);
        }
      } catch (err) {
        if (!cancelled) {
          const message = err instanceof Error && err.message ? err.message : label("formatLoadError", "Failed to load address configuration");
          flash(message, "error");
        }
      } finally {
        if (!cancelled) setFormatLoading(false);
      }
    }
    void loadFormatValue();
    return () => {
      cancelled = true;
    };
  }, [formatContext, label, loadFormat, scopeVersion]);
  const openCreateForm = React.useCallback(() => {
    resetForm();
    setIsFormOpen(true);
  }, [resetForm]);
  const handleCancel = React.useCallback(() => {
    resetForm();
    setIsFormOpen(false);
  }, [resetForm]);
  const handleEdit = React.useCallback((value) => {
    setDraft({
      name: value.name ?? "",
      purpose: value.purpose ?? "",
      companyName: value.companyName ?? "",
      addressLine1: value.addressLine1 ?? "",
      addressLine2: value.addressLine2 ?? "",
      buildingNumber: value.buildingNumber ?? "",
      flatNumber: value.flatNumber ?? "",
      city: value.city ?? "",
      region: value.region ?? "",
      postalCode: value.postalCode ?? "",
      country: value.country ?? "",
      isPrimary: value.isPrimary ?? false
    });
    setEditingId(value.id);
    setIsFormOpen(true);
    setFieldErrors({});
    setGeneralError(null);
  }, []);
  const validate = React.useCallback(() => {
    const errors = {};
    if (!draft.addressLine1.trim()) {
      errors.addressLine1 = label("validation.required", "{{field}} is required").replace("{{field}}", line1FieldLabel);
    }
    if (Object.keys(errors).length > 0) {
      setFieldErrors(errors);
      return false;
    }
    return true;
  }, [draft.addressLine1, label, line1FieldLabel]);
  const handleSave = React.useCallback(async () => {
    if (!validate()) return;
    setSaving(true);
    setGeneralError(null);
    try {
      const payload = {
        name: normalizeOptional(draft.name),
        purpose: normalizeOptional(draft.purpose),
        companyName: normalizeOptional(draft.companyName),
        addressLine1: draft.addressLine1.trim(),
        addressLine2: normalizeOptional(draft.addressLine2),
        buildingNumber: normalizeOptional(draft.buildingNumber),
        flatNumber: normalizeOptional(draft.flatNumber),
        city: normalizeOptional(draft.city),
        region: normalizeOptional(draft.region),
        postalCode: normalizeOptional(draft.postalCode),
        country: normalizeOptional(draft.country)?.toUpperCase(),
        isPrimary: draft.isPrimary
      };
      if (editingId && onUpdate) {
        await onUpdate(editingId, payload);
      } else {
        await onCreate(payload);
      }
      resetForm();
      setIsFormOpen(false);
    } catch (err) {
      const details = extractValidationDetails(err);
      if (details.length) {
        const nextErrors = {};
        details.forEach((detail) => {
          const path = Array.isArray(detail.path) ? detail.path : [];
          const key = typeof path[0] === "string" ? path[0] : void 0;
          if (!key) return;
          const fieldKey = serverFieldMap[key];
          if (!fieldKey) return;
          const fieldLabel = fieldKey === "addressLine1" ? line1FieldLabel : fieldLabels[fieldKey] ?? key;
          nextErrors[fieldKey] = resolveFieldMessage(detail, fieldLabel, t, labelPrefix);
        });
        setFieldErrors(nextErrors);
        setGeneralError(label("validation.summary", "Please fix the highlighted fields."));
        return;
      }
      const message = err instanceof Error && err.message ? err.message : label("error", "Failed to save address");
      setGeneralError(message);
      flash(message, "error");
    } finally {
      setSaving(false);
    }
  }, [draft, editingId, fieldLabels, label, labelPrefix, onCreate, onUpdate, resetForm, t, validate]);
  const handleDelete = React.useCallback(
    async (id) => {
      if (!onDelete) return;
      setDeletingId(id);
      try {
        await onDelete(id);
        if (editingId === id) {
          resetForm();
          setIsFormOpen(false);
        }
      } catch (err) {
        const message = err instanceof Error && err.message ? err.message : label("error", "Failed to delete address");
        flash(message, "error");
      } finally {
        setDeletingId(null);
      }
    },
    [editingId, label, onDelete, resetForm]
  );
  const disableActions = saving || isSubmitting || deletingId !== null;
  const isEditing = editingId !== null;
  const addDisabled = disableActions || isEditing;
  const hasAddresses = addresses.length > 0;
  const emptyTitle = emptyStateTitle ?? emptyLabel;
  const emptyActionLabel = emptyStateActionLabel ?? label("add", "Add address");
  React.useEffect(() => {
    if (!onAddActionChange) return;
    onAddActionChange({ openCreateForm, addDisabled });
  }, [onAddActionChange, openCreateForm, addDisabled]);
  React.useEffect(
    () => () => {
      if (onAddActionChange) onAddActionChange(null);
    },
    [onAddActionChange]
  );
  const renderFormTile = React.useCallback(
    (key) => /* @__PURE__ */ jsxs(
      "div",
      {
        className: "rounded-lg border-2 border-dashed border-muted-foreground/50 bg-muted/30 p-4 text-sm",
        onKeyDown: (event) => {
          if (!(event.metaKey || event.ctrlKey)) return;
          if (event.key !== "Enter") return;
          event.preventDefault();
          if (disableActions) return;
          void handleSave();
        },
        children: [
          /* @__PURE__ */ jsxs("div", { className: "flex items-center justify-between text-xs font-semibold uppercase tracking-wide text-muted-foreground", children: [
            /* @__PURE__ */ jsx("span", { children: editingId ? label("editTitle", "Edit address") : label("addTitle", "Add address") }),
            /* @__PURE__ */ jsx(Button, { type: "button", variant: "ghost", size: "icon", onClick: handleCancel, disabled: disableActions, children: /* @__PURE__ */ jsx(X, { className: "h-4 w-4" }) })
          ] }),
          /* @__PURE__ */ jsxs("div", { className: "mt-3 space-y-3", children: [
            formatLoading ? /* @__PURE__ */ jsx("p", { className: "text-xs text-muted-foreground", children: label("formatLoading", "Loading address preferences\u2026") }) : null,
            /* @__PURE__ */ jsx(
              AddressEditor,
              {
                value: draft,
                onChange: (next) => {
                  setDraft(next);
                  if (Object.keys(fieldErrors).length) {
                    const nextErrors = { ...fieldErrors };
                    Object.keys(nextErrors).forEach((key2) => {
                      const candidate = next[key2];
                      if (candidate !== void 0 && candidate !== null && `${candidate}`.length) {
                        delete nextErrors[key2];
                      }
                    });
                    setFieldErrors(nextErrors);
                  }
                },
                format,
                t,
                disabled: disableActions,
                errors: fieldErrors,
                showFormatHint: !formatLoading,
                labelPrefix,
                addressTypesAdapter,
                addressTypesContext
              }
            ),
            generalError ? /* @__PURE__ */ jsx("p", { className: "text-xs text-red-600", children: generalError }) : null,
            /* @__PURE__ */ jsxs("div", { className: "flex flex-wrap justify-end gap-2", children: [
              /* @__PURE__ */ jsx(Button, { type: "button", variant: "outline", onClick: handleCancel, disabled: disableActions, children: label("cancel", "Cancel") }),
              /* @__PURE__ */ jsx(Button, { type: "button", onClick: handleSave, disabled: disableActions, children: saving ? /* @__PURE__ */ jsxs(Fragment, { children: [
                /* @__PURE__ */ jsx(Loader2, { className: "mr-2 h-4 w-4 animate-spin" }),
                editingId ? label("updating", "Updating\u2026") : label("saving", "Saving\u2026")
              ] }) : editingId ? label("update", "Update address") : label("save", "Save address") })
            ] })
          ] })
        ]
      },
      key
    ),
    [
      addressTypesAdapter,
      addressTypesContext,
      disableActions,
      draft,
      editingId,
      fieldErrors,
      format,
      formatLoading,
      handleCancel,
      handleSave,
      generalError,
      label,
      labelPrefix,
      saving,
      t
    ]
  );
  return /* @__PURE__ */ jsxs("div", { className: "space-y-4", children: [
    !hideAddButton && hasAddresses ? /* @__PURE__ */ jsx("div", { className: "flex justify-end", children: /* @__PURE__ */ jsxs(
      Button,
      {
        type: "button",
        variant: "outline",
        size: "sm",
        onClick: openCreateForm,
        disabled: addDisabled,
        children: [
          /* @__PURE__ */ jsx(Plus, { className: "mr-2 h-4 w-4" }),
          label("add", "Add address")
        ]
      }
    ) }) : null,
    hasAddresses ? /* @__PURE__ */ jsxs("div", { className: gridClassName, children: [
      addresses.map((address) => {
        if (isFormOpen && editingId === address.id) {
          return renderFormTile(`form-${address.id}`);
        }
        const isDeleting = deletingId === address.id;
        return /* @__PURE__ */ jsx(
          "div",
          {
            className: "group rounded-lg border border-border/70 bg-card p-4 text-sm transition hover:border-border",
            children: /* @__PURE__ */ jsxs("div", { className: "flex items-start justify-between gap-2", children: [
              /* @__PURE__ */ jsxs("div", { className: "space-y-1", children: [
                /* @__PURE__ */ jsxs("div", { className: "flex flex-wrap items-center gap-2", children: [
                  /* @__PURE__ */ jsx("p", { className: "text-sm font-semibold text-foreground", children: address.name ?? label("labelFallback", "Address") }),
                  address.isPrimary ? /* @__PURE__ */ jsx("span", { className: "rounded-full border border-border bg-muted px-2 py-0.5 text-overline font-semibold uppercase", children: label("primaryBadge", "Primary") }) : null
                ] }),
                address.purpose ? /* @__PURE__ */ jsx("p", { className: "text-xs text-muted-foreground", children: address.purpose }) : null,
                /* @__PURE__ */ jsx(AddressView, { address, format, className: "text-sm text-foreground" }),
                /* @__PURE__ */ jsx("p", { className: "text-xs text-muted-foreground", children: formatAddressString(address, format) })
              ] }),
              /* @__PURE__ */ jsxs("div", { className: "flex items-center gap-1 opacity-100 md:opacity-0 transition-opacity md:group-hover:opacity-100 focus-within:opacity-100", children: [
                /* @__PURE__ */ jsx(
                  Button,
                  {
                    type: "button",
                    variant: "ghost",
                    size: "icon",
                    onClick: () => handleEdit(address),
                    disabled: disableActions,
                    children: /* @__PURE__ */ jsx(Pencil, { className: "h-4 w-4" })
                  }
                ),
                /* @__PURE__ */ jsx(
                  Button,
                  {
                    type: "button",
                    variant: "ghost",
                    size: "icon",
                    onClick: () => handleDelete(address.id),
                    disabled: disableActions,
                    children: isDeleting ? /* @__PURE__ */ jsx("span", { className: "relative flex h-4 w-4 items-center justify-center text-destructive", children: /* @__PURE__ */ jsx("span", { className: "absolute h-4 w-4 animate-spin rounded-full border border-destructive border-t-transparent" }) }) : /* @__PURE__ */ jsx(Trash2, { className: "h-4 w-4" })
                  }
                )
              ] })
            ] })
          },
          address.id
        );
      }),
      isFormOpen && !editingId ? renderFormTile("create") : null
    ] }) : isFormOpen ? /* @__PURE__ */ jsx("div", { className: gridClassName, children: renderFormTile("create") }) : /* @__PURE__ */ jsx(
      TabEmptyState,
      {
        title: emptyTitle,
        action: {
          label: emptyActionLabel,
          onClick: openCreateForm,
          disabled: addDisabled
        }
      }
    )
  ] });
}
var AddressTiles_default = AddressTiles;
export {
  AddressTiles,
  AddressTiles_default as default
};
//# sourceMappingURL=AddressTiles.js.map
