"use client";
import { Fragment, 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 "@open-mercato/ui/primitives/button";
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 { useAddressTypes } from "./detail/hooks/useAddressTypes.js";
function AddressEditor({
  value,
  onChange,
  format,
  t,
  disabled = false,
  errors = {},
  hidePrimaryToggle = false,
  showFormatHint = true,
  showCoordinateFields = false
}) {
  const pathname = usePathname();
  const searchParams = useSearchParams();
  const { options: addressTypes, loading: addressTypesLoading, error: addressTypeError, createType } = useAddressTypes(t);
  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]
  );
  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 ?? "",
    ...showCoordinateFields ? { latitude: value.latitude ?? "", longitude: value.longitude ?? "" } : {},
    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("/backend/config/customers", returnTo),
    [returnTo]
  );
  const handleTypeSubmit = React.useCallback(
    async (event) => {
      event.preventDefault();
      const trimmed = typeValue.trim();
      if (!trimmed.length) {
        setTypeFormError(t("customers.people.detail.addresses.types.emptyError", "Please provide a value"));
        return;
      }
      setTypeFormError(null);
      await createType(trimmed);
      setTypeDialogOpen(false);
      setTypeValue("");
    },
    [createType, t, typeValue]
  );
  const inputClass = (field) => [
    "w-full rounded-md border px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-ring",
    errors[field] ? "border-status-error-border focus:ring-status-error-border" : "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: t("customers.people.detail.addresses.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 ? t("customers.people.detail.addresses.types.loading", "Loading\u2026") : t("customers.people.detail.addresses.types.placeholder", "Address type")
                    }
                  )
                }
              ),
              /* @__PURE__ */ jsx(SelectContent, { children: addressTypes.map((entry) => /* @__PURE__ */ jsx(SelectItem, { value: entry.value, children: entry.label }, entry.value)) })
            ]
          }
        ),
        /* @__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: t("customers.people.detail.addresses.types.add", "Add address type") }),
              /* @__PURE__ */ jsx(DialogDescription, { children: t("customers.people.detail.addresses.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: t("customers.people.detail.addresses.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: t("customers.people.detail.addresses.types.cancel", "Cancel") }),
                /* @__PURE__ */ jsx(Button, { type: "submit", disabled: disabled || !typeValue.trim(), children: t("customers.people.detail.addresses.types.save", "Save") })
              ] })
            ] })
          ] })
        ] }),
        /* @__PURE__ */ jsx(
          Button,
          {
            asChild: true,
            type: "button",
            variant: "ghost",
            size: "icon",
            className: "shrink-0",
            disabled,
            title: t("customers.people.detail.addresses.types.manage", "Manage address types"),
            children: /* @__PURE__ */ jsx(
              Link,
              {
                href: manageAddressTypesHref,
                "aria-label": t("customers.people.detail.addresses.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: t("customers.people.detail.addresses.fields.companyName", "Company name"),
        value: current.companyName,
        onChange: (evt) => update("companyName", evt.target.value),
        disabled,
        "aria-invalid": errors.companyName ? "true" : void 0
      }
    ),
    showFormatHint ? /* @__PURE__ */ jsx("p", { className: "text-xs text-muted-foreground", children: format === "street_first" ? t("customers.people.detail.addresses.streetFormatHint", "Street-first layout is active.") : t("customers.people.detail.addresses.lineFormatHint", "Address-line layout is active.") }) : null,
    /* @__PURE__ */ jsxs("div", { className: "grid grid-cols-1 gap-2 sm:grid-cols-2", children: [
      /* @__PURE__ */ jsx(
        Input,
        {
          className: inputClass("addressLine1"),
          placeholder: format === "street_first" ? t("customers.people.detail.addresses.fields.street", "Street") : t("customers.people.detail.addresses.fields.line1", "Address line 1"),
          value: current.addressLine1,
          onChange: (evt) => update("addressLine1", evt.target.value),
          disabled,
          "aria-invalid": errors.addressLine1 ? "true" : void 0
        }
      ),
      errors.addressLine1 ? /* @__PURE__ */ jsx("p", { className: "text-xs text-destructive sm:col-span-2", children: errors.addressLine1 }) : null,
      format === "street_first" ? /* @__PURE__ */ jsxs(Fragment, { children: [
        /* @__PURE__ */ jsx(
          Input,
          {
            className: inputClass("buildingNumber"),
            placeholder: t("customers.people.detail.addresses.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: t("customers.people.detail.addresses.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("addressLine2"),
            placeholder: t("customers.people.detail.addresses.fields.streetExtra", "Address line 2"),
            value: current.addressLine2,
            onChange: (evt) => update("addressLine2", evt.target.value),
            disabled,
            "aria-invalid": errors.addressLine2 ? "true" : void 0
          }
        ),
        errors.addressLine2 ? /* @__PURE__ */ jsx("p", { className: "text-xs text-destructive sm:col-span-2", children: errors.addressLine2 }) : null
      ] }) : /* @__PURE__ */ jsxs(Fragment, { children: [
        /* @__PURE__ */ jsx(
          Input,
          {
            className: inputClass("addressLine2"),
            placeholder: t("customers.people.detail.addresses.fields.line2", "Address line 2"),
            value: current.addressLine2,
            onChange: (evt) => update("addressLine2", evt.target.value),
            disabled,
            "aria-invalid": errors.addressLine2 ? "true" : void 0
          }
        ),
        errors.addressLine2 ? /* @__PURE__ */ jsx("p", { className: "text-xs text-destructive sm:col-span-2", children: errors.addressLine2 }) : null
      ] }),
      /* @__PURE__ */ jsx(
        Input,
        {
          className: inputClass("city"),
          placeholder: t("customers.people.detail.addresses.fields.city", "City"),
          value: current.city,
          onChange: (evt) => update("city", evt.target.value),
          disabled,
          "aria-invalid": errors.city ? "true" : void 0
        }
      ),
      errors.city ? /* @__PURE__ */ jsx("p", { className: "text-xs text-destructive", children: errors.city }) : null,
      /* @__PURE__ */ jsx(
        Input,
        {
          className: inputClass("region"),
          placeholder: t("customers.people.detail.addresses.fields.region", "Region/state"),
          value: current.region,
          onChange: (evt) => update("region", evt.target.value),
          disabled,
          "aria-invalid": errors.region ? "true" : void 0
        }
      ),
      errors.region ? /* @__PURE__ */ jsx("p", { className: "text-xs text-destructive", children: errors.region }) : null,
      /* @__PURE__ */ jsx(
        Input,
        {
          className: inputClass("postalCode"),
          placeholder: t("customers.people.detail.addresses.fields.postalCode", "Postal code"),
          value: current.postalCode,
          onChange: (evt) => update("postalCode", evt.target.value),
          disabled,
          "aria-invalid": errors.postalCode ? "true" : void 0
        }
      ),
      errors.postalCode ? /* @__PURE__ */ jsx("p", { className: "text-xs text-destructive", children: errors.postalCode }) : null,
      /* @__PURE__ */ jsxs(
        Dialog,
        {
          open: countryDialogOpen,
          onOpenChange: (open) => {
            setCountryDialogOpen(open);
            if (!open) setCountryQuery("");
          },
          children: [
            /* @__PURE__ */ jsx(DialogTrigger, { asChild: true, children: /* @__PURE__ */ jsxs(
              Button,
              {
                type: "button",
                variant: "outline",
                className: `${inputClass("country")} h-10 w-full justify-between`,
                disabled,
                "aria-invalid": errors.country ? "true" : void 0,
                children: [
                  /* @__PURE__ */ jsx("span", { className: "truncate text-left", children: selectedCountry ? `${selectedCountry.label}` : t("customers.people.detail.addresses.countryPlaceholder", "Select country") }),
                  /* @__PURE__ */ jsx("span", { className: "ml-2 text-xs text-muted-foreground", children: selectedCountry ? selectedCountry.code : null })
                ]
              }
            ) }),
            /* @__PURE__ */ jsxs(DialogContent, { className: "sm:max-w-md", children: [
              /* @__PURE__ */ jsxs(DialogHeader, { children: [
                /* @__PURE__ */ jsx(DialogTitle, { children: t("customers.people.detail.addresses.countryDialogTitle", "Select country") }),
                /* @__PURE__ */ jsx(DialogDescription, { children: t("customers.people.detail.addresses.countryDialogDescription", "Search and choose an ISO country code.") })
              ] }),
              /* @__PURE__ */ jsxs("div", { className: "space-y-3", children: [
                /* @__PURE__ */ jsx(
                  Input,
                  {
                    placeholder: t("customers.people.detail.addresses.countrySearch", "Search country"),
                    value: countryQuery,
                    onChange: (evt) => setCountryQuery(evt.target.value)
                  }
                ),
                /* @__PURE__ */ jsx("div", { className: "max-h-64 overflow-y-auto rounded border divide-y", children: filteredCountryOptions.length === 0 ? /* @__PURE__ */ jsx("p", { className: "px-3 py-2 text-sm text-muted-foreground", children: t("customers.people.detail.addresses.countryEmpty", "No matches found") }) : filteredCountryOptions.map((option) => /* @__PURE__ */ jsxs(
                  Button,
                  {
                    variant: "ghost",
                    size: "sm",
                    className: "w-full justify-between rounded-none font-normal",
                    onClick: () => {
                      update("country", option.code);
                      setCountryDialogOpen(false);
                      setCountryQuery("");
                    },
                    children: [
                      /* @__PURE__ */ jsx("span", { className: "truncate", children: option.label }),
                      /* @__PURE__ */ jsx("span", { className: "text-xs text-muted-foreground", children: option.code })
                    ]
                  },
                  option.code
                )) }),
                /* @__PURE__ */ jsxs("div", { className: "flex items-center justify-between gap-2", children: [
                  /* @__PURE__ */ jsx(
                    Button,
                    {
                      type: "button",
                      variant: "outline",
                      onClick: () => {
                        update("country", "");
                        setCountryDialogOpen(false);
                        setCountryQuery("");
                      },
                      disabled,
                      children: t("customers.people.detail.addresses.countryClear", "Clear")
                    }
                  ),
                  /* @__PURE__ */ jsx(Button, { type: "button", onClick: () => setCountryDialogOpen(false), children: t("customers.people.detail.addresses.countryClose", "Done") })
                ] })
              ] })
            ] })
          ]
        }
      ),
      errors.country ? /* @__PURE__ */ jsx("p", { className: "text-xs text-destructive", children: errors.country }) : null,
      showCoordinateFields ? /* @__PURE__ */ jsxs(Fragment, { children: [
        /* @__PURE__ */ jsx(
          Input,
          {
            className: inputClass("latitude"),
            placeholder: t("customers.people.detail.addresses.fields.latitude", "Latitude"),
            "aria-label": t("customers.people.detail.addresses.fields.latitude", "Latitude"),
            inputMode: "decimal",
            value: current.latitude ?? "",
            onChange: (evt) => update("latitude", evt.target.value),
            disabled,
            "aria-invalid": errors.latitude ? "true" : void 0
          }
        ),
        errors.latitude ? /* @__PURE__ */ jsx("p", { className: "text-xs text-destructive", children: errors.latitude }) : null,
        /* @__PURE__ */ jsx(
          Input,
          {
            className: inputClass("longitude"),
            placeholder: t("customers.people.detail.addresses.fields.longitude", "Longitude"),
            "aria-label": t("customers.people.detail.addresses.fields.longitude", "Longitude"),
            inputMode: "decimal",
            value: current.longitude ?? "",
            onChange: (evt) => update("longitude", evt.target.value),
            disabled,
            "aria-invalid": errors.longitude ? "true" : void 0
          }
        ),
        errors.longitude ? /* @__PURE__ */ jsx("p", { className: "text-xs text-destructive", children: errors.longitude }) : null
      ] }) : null
    ] }),
    !hidePrimaryToggle ? /* @__PURE__ */ jsxs("label", { className: "inline-flex items-center gap-2 text-sm", children: [
      /* @__PURE__ */ jsx(
        "input",
        {
          type: "checkbox",
          checked: current.isPrimary,
          onChange: (evt) => update("isPrimary", evt.target.checked),
          disabled,
          "aria-invalid": errors.isPrimary ? "true" : void 0
        }
      ),
      /* @__PURE__ */ jsx("span", { children: t("customers.people.detail.addresses.fields.primary", "Set as primary") })
    ] }) : null,
    errors.isPrimary ? /* @__PURE__ */ jsx("p", { className: "text-xs text-destructive", children: errors.isPrimary }) : null
  ] });
}
var AddressEditor_default = AddressEditor;
export {
  AddressEditor,
  AddressEditor_default as default
};
//# sourceMappingURL=AddressEditor.js.map
