"use client";

import { useEffect, useRef, useState } from "react";
import { autocompleteDhlAddress, type DhlAddressSuggestion } from "../../lib/shippingDhl";

// Wraps a plain street-address input with a DHL DataFactory suggestion
// dropdown. Completely invisible/inert when the tenant doesn't have
// autocomplete activated (dhl-settings.autocompleteEnabled off) — the proxy
// route just returns an empty suggestions array in that case (see
// app/api/checkout/autocomplete-address/route.ts), so this degrades to a
// plain text input with no dropdown ever appearing, same "no half-built UI
// when a feature is off" convention as WishlistButton/searchEnabled.
//
// Styling duplicates FormField's classes (defined locally in
// CheckoutContent.tsx, not exported) rather than importing it, to keep this
// component usable on its own.
export function AddressAutocomplete({
  label,
  name,
  value,
  onChange,
  onBlur,
  onSelectSuggestion,
  error,
  placeholder,
  autoComplete,
  required,
  wrapperClassName = "flex-1 min-w-0",
}: {
  label: string;
  name?: string;
  value: string;
  onChange: (value: string) => void;
  onBlur?: (e: React.FocusEvent<HTMLInputElement>) => void;
  onSelectSuggestion: (suggestion: DhlAddressSuggestion) => void;
  error?: string;
  placeholder?: string;
  autoComplete?: string;
  required?: boolean;
  wrapperClassName?: string;
}) {
  const [suggestions, setSuggestions] = useState<DhlAddressSuggestion[]>([]);
  const [open, setOpen] = useState(false);
  const debounceRef = useRef<ReturnType<typeof setTimeout> | null>(null);

  useEffect(() => {
    if (debounceRef.current) clearTimeout(debounceRef.current);
    if (value.trim().length < 3) {
      setSuggestions([]);
      return;
    }
    debounceRef.current = setTimeout(async () => {
      const res = await fetch(`/api/checkout/autocomplete-address?query=${encodeURIComponent(value)}`);
      const data = await res.json().catch(() => ({ ok: false, suggestions: [] }));
      setSuggestions(data.ok ? data.suggestions : []);
    }, 300);
    return () => {
      if (debounceRef.current) clearTimeout(debounceRef.current);
    };
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [value]);

  return (
    <label className={`relative flex flex-col gap-2 items-start ${wrapperClassName}`}>
      <span className="text-label text-text-muted">{label}</span>
      <input
        name={name}
        type="text"
        value={value}
        onChange={(e) => {
          onChange(e.target.value);
          setOpen(true);
        }}
        onFocus={() => setOpen(true)}
        // Delayed so a click on a suggestion below (which itself fires a
        // blur first) still registers before the dropdown unmounts.
        onBlur={(e) => {
          setTimeout(() => setOpen(false), 150);
          onBlur?.(e);
        }}
        placeholder={placeholder}
        autoComplete={autoComplete}
        required={required}
        aria-invalid={error ? true : undefined}
        className={`w-full border rounded-sm px-4 py-3 text-body-sm text-text-primary outline-none focus:border-brand transition-colors ${
          error ? "border-red-600" : "border-border"
        }`}
      />
      {error && <span className="text-label text-red-600">{error}</span>}
      {open && suggestions.length > 0 && (
        <ul className="absolute top-full left-0 right-0 z-10 mt-1 max-h-60 overflow-y-auto rounded-sm border border-border bg-background shadow-lg">
          {suggestions.map((s, i) => (
            <li key={i}>
              <button
                type="button"
                onClick={() => {
                  onChange(`${s.street}${s.houseNumber ? ` ${s.houseNumber}` : ""}`);
                  onSelectSuggestion(s);
                  setOpen(false);
                }}
                className="w-full text-left px-4 py-2 text-body-sm text-text-primary hover:bg-brand/10 transition-colors"
              >
                {s.street}
                {s.houseNumber ? ` ${s.houseNumber}` : ""}, {s.zip} {s.city}
              </button>
            </li>
          ))}
        </ul>
      )}
    </label>
  );
}
