"use client";
import { jsx, jsxs } from "react/jsx-runtime";
import * as React from "react";
import Link from "next/link";
import { usePathname, useSearchParams } from "next/navigation";
import { Plus, Settings } from "lucide-react";
import { Button } from "../../primitives/button.js";
import { Input } from "@open-mercato/ui/primitives/input";
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue
} from "@open-mercato/ui/primitives/select";
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogFooter,
  DialogHeader,
  DialogTitle,
  DialogTrigger
} from "@open-mercato/ui/primitives/dialog";
import { buildCountryOptions } from "@open-mercato/shared/lib/location/countries";
import { buildHrefWithReturnTo } from "@open-mercato/shared/lib/navigation/returnTo";
import { cn } from "@open-mercato/shared/lib/utils";
function AddressEditor({
  value,
  onChange,
  format,
  t,
  labelPrefix = "customers.people.detail.addresses",
  disabled = false,
  errors = {},
  hidePrimaryToggle = false,
  showFormatHint = true,
  addressTypesAdapter,
  addressTypesContext
}) {
  const pathname = usePathname();
  const searchParams = useSearchParams();
  const label = React.useCallback(
    (suffix, fallback, params) => t(`${labelPrefix}.${suffix}`, fallback, params),
    [labelPrefix, t]
  );
  const [addressTypes, setAddressTypes] = React.useState([]);
  const [addressTypesLoading, setAddressTypesLoading] = React.useState(false);
  const [addressTypeError, setAddressTypeError] = React.useState(null);
  const [typeDialogOpen, setTypeDialogOpen] = React.useState(false);
  const [typeValue, setTypeValue] = React.useState("");
  const [typeFormError, setTypeFormError] = React.useState(null);
  const [countryDialogOpen, setCountryDialogOpen] = React.useState(false);
  const [countryQuery, setCountryQuery] = React.useState("");
  const countryOptions = React.useMemo(
    () => buildCountryOptions({
      transformLabel: (code, fallback) => t(`customers.countries.${code.toLowerCase()}`, fallback ?? code)
    }),
    [t]
  );
  React.useEffect(() => {
    let cancelled = false;
    const load = async () => {
      if (!addressTypesAdapter) {
        setAddressTypes([]);
        setAddressTypeError(null);
        return;
      }
      setAddressTypesLoading(true);
      try {
        const result = await addressTypesAdapter.list(addressTypesContext);
        if (!cancelled) {
          setAddressTypes(Array.isArray(result) ? result : []);
          setAddressTypeError(null);
        }
      } catch (err) {
        if (!cancelled) {
          setAddressTypes([]);
          setAddressTypeError(label("types.loadError", "Failed to load address types"));
        }
      } finally {
        if (!cancelled) setAddressTypesLoading(false);
      }
    };
    load().catch(() => {
    });
    return () => {
      cancelled = true;
    };
  }, [addressTypesAdapter, addressTypesContext, label]);
  const current = {
    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
  };
  const update = React.useCallback(
    (key, nextValue) => {
      onChange({ ...current, [key]: nextValue });
    },
    [current, onChange]
  );
  const filteredCountryOptions = React.useMemo(() => {
    const query = countryQuery.trim().toLowerCase();
    if (!query.length) return countryOptions;
    return countryOptions.filter(
      (option) => option.label.toLowerCase().includes(query) || option.code.toLowerCase().includes(query)
    );
  }, [countryOptions, countryQuery]);
  const selectedCountry = React.useMemo(() => {
    const code = (current.country ?? "").toUpperCase();
    if (!code.length) return null;
    return countryOptions.find((option) => option.code === code) ?? null;
  }, [countryOptions, current.country]);
  const returnTo = React.useMemo(() => {
    const query = searchParams?.toString() ?? "";
    if (!pathname) return null;
    return query.length ? `${pathname}?${query}` : pathname;
  }, [pathname, searchParams]);
  const manageAddressTypesHref = React.useMemo(
    () => buildHrefWithReturnTo(addressTypesAdapter?.manageHref ?? "/backend/config/dictionaries", returnTo),
    [addressTypesAdapter?.manageHref, returnTo]
  );
  const handleTypeSubmit = React.useCallback(
    async (event) => {
      event.preventDefault();
      const trimmed = typeValue.trim();
      if (!trimmed.length) {
        setTypeFormError(label("types.emptyError", "Please provide a value"));
        return;
      }
      if (!addressTypesAdapter?.create) return;
      setTypeFormError(null);
      const created = await addressTypesAdapter.create(trimmed, addressTypesContext);
      if (created) {
        setAddressTypes((prev) => {
          const map = new Map(prev.map((entry) => [entry.value, entry]));
          map.set(created.value, created);
          return Array.from(map.values()).sort((a, b) => a.label.localeCompare(b.label));
        });
      }
      setTypeDialogOpen(false);
      setTypeValue("");
    },
    [addressTypesAdapter, addressTypesContext, label, typeValue]
  );
  const inputClass = (field) => [
    "w-full rounded-md border px-3 py-2 text-sm focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring",
    errors[field] ? "border-red-500 aria-invalid:ring-destructive" : "border-input bg-background"
  ].join(" ");
  return /* @__PURE__ */ jsxs("div", { className: "space-y-3", children: [
    /* @__PURE__ */ jsxs("div", { className: "grid gap-2 sm:grid-cols-2", children: [
      /* @__PURE__ */ jsx(
        Input,
        {
          className: inputClass("name"),
          placeholder: label("fields.label", "Label"),
          value: current.name,
          onChange: (evt) => update("name", evt.target.value),
          disabled,
          "aria-invalid": errors.name ? "true" : void 0
        }
      ),
      /* @__PURE__ */ jsxs("div", { className: "flex gap-2", children: [
        /* @__PURE__ */ jsxs(
          Select,
          {
            value: current.purpose || void 0,
            onValueChange: (next) => update("purpose", next ?? ""),
            disabled,
            children: [
              /* @__PURE__ */ jsx(
                SelectTrigger,
                {
                  className: errors.purpose ? "border-destructive" : void 0,
                  "aria-invalid": errors.purpose ? "true" : void 0,
                  children: /* @__PURE__ */ jsx(
                    SelectValue,
                    {
                      placeholder: addressTypesLoading ? label("types.loading", "Loading\u2026") : label("types.placeholder", "Address type")
                    }
                  )
                }
              ),
              /* @__PURE__ */ jsx(SelectContent, { children: addressTypes.map((entry) => /* @__PURE__ */ jsx(SelectItem, { value: entry.value, children: entry.label }, entry.value)) })
            ]
          }
        ),
        addressTypesAdapter?.create ? /* @__PURE__ */ jsxs(Dialog, { open: typeDialogOpen, onOpenChange: setTypeDialogOpen, children: [
          /* @__PURE__ */ jsx(DialogTrigger, { asChild: true, children: /* @__PURE__ */ jsx(Button, { type: "button", variant: "outline", size: "icon", className: "shrink-0", disabled, children: /* @__PURE__ */ jsx(Plus, { className: "h-4 w-4" }) }) }),
          /* @__PURE__ */ jsxs(DialogContent, { className: "sm:max-w-md", children: [
            /* @__PURE__ */ jsxs(DialogHeader, { children: [
              /* @__PURE__ */ jsx(DialogTitle, { children: label("types.add", "Add address type") }),
              /* @__PURE__ */ jsx(DialogDescription, { children: label("types.addHint", "Create a new address type for reuse.") })
            ] }),
            /* @__PURE__ */ jsxs("form", { className: "space-y-3", onSubmit: handleTypeSubmit, children: [
              /* @__PURE__ */ jsx(
                Input,
                {
                  autoFocus: true,
                  value: typeValue,
                  onChange: (evt) => {
                    setTypeValue(evt.target.value);
                    if (typeFormError) setTypeFormError(null);
                  },
                  placeholder: label("types.placeholder", "Address type"),
                  disabled,
                  "aria-invalid": typeFormError ? "true" : void 0
                }
              ),
              typeFormError ? /* @__PURE__ */ jsx("p", { className: "text-sm text-destructive", children: typeFormError }) : null,
              /* @__PURE__ */ jsxs(DialogFooter, { children: [
                /* @__PURE__ */ jsx(Button, { type: "button", variant: "outline", onClick: () => setTypeDialogOpen(false), disabled, children: label("types.cancel", "Cancel") }),
                /* @__PURE__ */ jsx(Button, { type: "submit", disabled: disabled || !typeValue.trim(), children: label("types.save", "Save") })
              ] })
            ] })
          ] })
        ] }) : null,
        /* @__PURE__ */ jsx(
          Button,
          {
            asChild: true,
            type: "button",
            variant: "ghost",
            size: "icon",
            className: "shrink-0",
            disabled,
            title: label("types.manage", "Manage address types"),
            children: /* @__PURE__ */ jsx(
              Link,
              {
                href: manageAddressTypesHref,
                "aria-label": label("types.manage", "Manage address types"),
                children: /* @__PURE__ */ jsx(Settings, { className: "h-4 w-4" })
              }
            )
          }
        )
      ] })
    ] }),
    errors.purpose ? /* @__PURE__ */ jsx("p", { className: "text-xs text-destructive", children: errors.purpose }) : null,
    addressTypeError ? /* @__PURE__ */ jsx("p", { className: "text-xs text-destructive", children: addressTypeError }) : null,
    /* @__PURE__ */ jsx(
      Input,
      {
        className: inputClass("companyName"),
        placeholder: label("fields.companyName", "Company name"),
        value: current.companyName,
        onChange: (evt) => update("companyName", evt.target.value),
        disabled,
        "aria-invalid": errors.companyName ? "true" : void 0
      }
    ),
    format === "street_first" ? /* @__PURE__ */ jsxs("div", { className: "grid gap-2 sm:grid-cols-[1.5fr,0.7fr,0.7fr]", children: [
      /* @__PURE__ */ jsx(
        Input,
        {
          className: inputClass("addressLine1"),
          placeholder: label("fields.street", "Street"),
          value: current.addressLine1,
          onChange: (evt) => update("addressLine1", evt.target.value),
          disabled,
          "aria-invalid": errors.addressLine1 ? "true" : void 0
        }
      ),
      /* @__PURE__ */ jsx(
        Input,
        {
          className: inputClass("buildingNumber"),
          placeholder: label("fields.buildingNumber", "Building number"),
          value: current.buildingNumber,
          onChange: (evt) => update("buildingNumber", evt.target.value),
          disabled,
          "aria-invalid": errors.buildingNumber ? "true" : void 0
        }
      ),
      /* @__PURE__ */ jsx(
        Input,
        {
          className: inputClass("flatNumber"),
          placeholder: label("fields.flatNumber", "Flat number"),
          value: current.flatNumber,
          onChange: (evt) => update("flatNumber", evt.target.value),
          disabled,
          "aria-invalid": errors.flatNumber ? "true" : void 0
        }
      )
    ] }) : /* @__PURE__ */ jsx(
      Input,
      {
        className: inputClass("addressLine1"),
        placeholder: label("fields.line1", "Address line 1"),
        value: current.addressLine1,
        onChange: (evt) => update("addressLine1", evt.target.value),
        disabled,
        "aria-invalid": errors.addressLine1 ? "true" : void 0
      }
    ),
    /* @__PURE__ */ jsx(
      Input,
      {
        className: inputClass("addressLine2"),
        placeholder: label("fields.line2", "Address line 2"),
        value: current.addressLine2,
        onChange: (evt) => update("addressLine2", evt.target.value),
        disabled,
        "aria-invalid": errors.addressLine2 ? "true" : void 0
      }
    ),
    format !== "street_first" ? /* @__PURE__ */ jsxs("div", { className: "grid gap-2 sm:grid-cols-[1.5fr,0.7fr,0.7fr]", children: [
      /* @__PURE__ */ jsx(
        Input,
        {
          className: inputClass("buildingNumber"),
          placeholder: label("fields.buildingNumber", "Building number"),
          value: current.buildingNumber,
          onChange: (evt) => update("buildingNumber", evt.target.value),
          disabled,
          "aria-invalid": errors.buildingNumber ? "true" : void 0
        }
      ),
      /* @__PURE__ */ jsx(
        Input,
        {
          className: inputClass("flatNumber"),
          placeholder: label("fields.flatNumber", "Flat number"),
          value: current.flatNumber,
          onChange: (evt) => update("flatNumber", evt.target.value),
          disabled,
          "aria-invalid": errors.flatNumber ? "true" : void 0
        }
      )
    ] }) : null,
    /* @__PURE__ */ jsxs("div", { className: "grid gap-2 sm:grid-cols-2", children: [
      /* @__PURE__ */ jsx(
        Input,
        {
          className: inputClass("city"),
          placeholder: label("fields.city", "City"),
          value: current.city,
          onChange: (evt) => update("city", evt.target.value),
          disabled,
          "aria-invalid": errors.city ? "true" : void 0
        }
      ),
      /* @__PURE__ */ jsx(
        Input,
        {
          className: inputClass("region"),
          placeholder: label("fields.region", "Region"),
          value: current.region,
          onChange: (evt) => update("region", evt.target.value),
          disabled,
          "aria-invalid": errors.region ? "true" : void 0
        }
      )
    ] }),
    /* @__PURE__ */ jsxs("div", { className: "grid gap-2 sm:grid-cols-2", children: [
      /* @__PURE__ */ jsx(
        Input,
        {
          className: inputClass("postalCode"),
          placeholder: label("fields.postalCode", "Postal code"),
          value: current.postalCode,
          onChange: (evt) => update("postalCode", evt.target.value),
          disabled,
          "aria-invalid": errors.postalCode ? "true" : void 0
        }
      ),
      /* @__PURE__ */ jsxs(Dialog, { open: countryDialogOpen, onOpenChange: setCountryDialogOpen, children: [
        /* @__PURE__ */ jsx(DialogTrigger, { asChild: true, children: /* @__PURE__ */ jsx(Button, { type: "button", variant: "ghost", className: cn(inputClass("country"), "cursor-pointer"), disabled, children: selectedCountry?.label ?? label("fields.country", "Country") }) }),
        /* @__PURE__ */ jsxs(DialogContent, { className: "sm:max-w-lg", children: [
          /* @__PURE__ */ jsxs(DialogHeader, { children: [
            /* @__PURE__ */ jsx(DialogTitle, { children: label("country.title", "Choose a country") }),
            /* @__PURE__ */ jsx(DialogDescription, { children: label("country.subtitle", "Search for a country") })
          ] }),
          /* @__PURE__ */ jsxs("div", { className: "space-y-3", children: [
            /* @__PURE__ */ jsx(
              Input,
              {
                placeholder: label("country.search", "Search countries"),
                value: countryQuery,
                onChange: (evt) => setCountryQuery(evt.target.value)
              }
            ),
            /* @__PURE__ */ jsx("div", { className: "max-h-64 overflow-auto rounded-md border border-border/70", children: /* @__PURE__ */ jsx("ul", { className: "divide-y divide-border/50", children: filteredCountryOptions.map((option) => /* @__PURE__ */ jsx("li", { children: /* @__PURE__ */ jsxs(
              Button,
              {
                variant: "ghost",
                size: "sm",
                className: "w-full justify-between font-normal rounded-none",
                onClick: () => {
                  update("country", option.code);
                  setCountryDialogOpen(false);
                },
                children: [
                  /* @__PURE__ */ jsx("span", { children: option.label }),
                  /* @__PURE__ */ jsx("span", { className: "text-xs text-muted-foreground", children: option.code })
                ]
              }
            ) }, option.code)) }) })
          ] })
        ] })
      ] })
    ] }),
    showFormatHint ? /* @__PURE__ */ jsx("p", { className: "text-xs text-muted-foreground", children: label("formatHint", "Format based on address settings") }) : null,
    !hidePrimaryToggle ? /* @__PURE__ */ jsxs("label", { className: "flex items-center gap-2 text-sm text-muted-foreground", children: [
      /* @__PURE__ */ jsx(
        "input",
        {
          type: "checkbox",
          checked: current.isPrimary,
          onChange: (evt) => update("isPrimary", evt.target.checked),
          disabled
        }
      ),
      label("fields.primary", "Primary address")
    ] }) : null
  ] });
}
var AddressEditor_default = AddressEditor;
export {
  AddressEditor,
  AddressEditor_default as default
};
//# sourceMappingURL=AddressEditor.js.map
