"use client";

import { useState, useRef, useEffect } from "react";
import { MapPin, Loader2 } from "lucide-react";

export interface PoiSuggestion {
  id: string;
  name: string;
  district: string;
  address: string;
  lat: number;
  lng: number;
}

interface PoiSearchFieldProps {
  poi: string;
  address: string;
  onSelect: (s: PoiSuggestion) => void;
  location?: string;
}

export default function PoiSearchField({ poi, address, onSelect, location }: PoiSearchFieldProps) {
  const [query, setQuery] = useState(poi);
  const [suggestions, setSuggestions] = useState<PoiSuggestion[]>([]);
  const [loading, setLoading] = useState(false);
  const [open, setOpen] = useState(false);
  const lastSelectedRef = useRef(poi);
  const timerRef = useRef<ReturnType<typeof setTimeout> | null>(null);

  useEffect(() => {
    if (timerRef.current) clearTimeout(timerRef.current);
    if (!query.trim() || query === lastSelectedRef.current) {
      setSuggestions([]);
      setOpen(false);
      return;
    }
    timerRef.current = setTimeout(async () => {
      setLoading(true);
      try {
        const params = new URLSearchParams({ keywords: query });
        if (location) params.set("location", location);
        const res = await fetch(`/api/location/suggest?${params}`);
        if (res.ok) {
          const data: PoiSuggestion[] = await res.json();
          setSuggestions(data);
          setOpen(data.length > 0);
        }
      } catch (e) { console.error("PoiSearchField fetch failed:", e); }
      finally { setLoading(false); }
    }, 400);
    return () => { if (timerRef.current) clearTimeout(timerRef.current); };
  }, [query, location]);

  return (
    <div className="flex flex-col gap-1">
      <span className="text-[11px] font-medium text-muted">地点</span>
      <div className="relative">
        <input
          type="text"
          value={query}
          onChange={(e) => setQuery(e.target.value)}
          placeholder="搜索地点名称..."
          className="h-9 w-full rounded-lg bg-elevated px-3 pr-8 text-sm text-foreground outline-none ring-1 ring-border focus:ring-purple-600"
        />
        {loading && (
          <Loader2 size={14} className="absolute right-2.5 top-2.5 animate-spin text-muted" />
        )}
      </div>
      {open && suggestions.length > 0 && (
        <div className="overflow-hidden rounded-lg bg-elevated ring-1 ring-border">
          {suggestions.map((s) => (
            <button
              key={s.id}
              type="button"
              onClick={() => {
                lastSelectedRef.current = s.name;
                setQuery(s.name);
                setOpen(false);
                setSuggestions([]);
                onSelect(s);
              }}
              className="flex w-full flex-col border-b border-border/40 px-3 py-2 text-left last:border-0 active:bg-purple-600/10"
            >
              <span className="text-xs font-medium text-foreground">{s.name}</span>
              <span className="truncate text-[10px] text-muted">{s.district} {s.address}</span>
            </button>
          ))}
        </div>
      )}
      {address && !open && (
        <p className="flex items-center gap-1 text-[10px] text-dim">
          <MapPin size={9} className="shrink-0" />
          {address}
        </p>
      )}
    </div>
  );
}
