"use client";

import { useState, useCallback, useRef, useEffect } from "react";
import { Search, Loader2, MapPin, Hash } from "lucide-react";
import { cn } from "@/shared/lib/utils";

export interface UatHit {
  siruta: string;
  name: string;
  county: string;
}

export interface FeatureHit {
  id: string;
  layerId: string;
  cadastralRef: string;
  areaValue?: number;
}

interface SearchResponse {
  q: string;
  uats?: UatHit[];
  features?: FeatureHit[];
  error?: string;
}

interface Props {
  onUatSelect: (uat: UatHit) => void;
  onFeatureSelect: (feature: FeatureHit) => void;
}

export function SearchBar({ onUatSelect, onFeatureSelect }: Props) {
  const [q, setQ] = useState("");
  const [loading, setLoading] = useState(false);
  const [results, setResults] = useState<SearchResponse | null>(null);
  const [open, setOpen] = useState(false);
  const debounceRef = useRef<ReturnType<typeof setTimeout> | null>(null);
  const wrapperRef = useRef<HTMLDivElement>(null);

  // Close dropdown when clicking outside
  useEffect(() => {
    const onClick = (e: MouseEvent) => {
      if (!wrapperRef.current?.contains(e.target as Node)) setOpen(false);
    };
    document.addEventListener("mousedown", onClick);
    return () => document.removeEventListener("mousedown", onClick);
  }, []);

  const runSearch = useCallback(async (query: string) => {
    if (query.trim().length < 2) {
      setResults(null);
      return;
    }
    setLoading(true);
    try {
      const res = await fetch(
        `/api/gis/search?q=${encodeURIComponent(query)}&limit=10`,
      );
      const data: SearchResponse = await res.json();
      setResults(data);
      setOpen(true);
    } catch {
      setResults({ q: query, error: "search_failed" });
    } finally {
      setLoading(false);
    }
  }, []);

  const handleChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    const val = e.target.value;
    setQ(val);
    if (debounceRef.current) clearTimeout(debounceRef.current);
    debounceRef.current = setTimeout(() => runSearch(val), 300);
  };

  const totalHits =
    (results?.uats?.length ?? 0) + (results?.features?.length ?? 0);

  return (
    <div ref={wrapperRef} className="relative w-72">
      <div className="relative">
        <Search className="absolute left-2 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground" />
        <input
          type="search"
          value={q}
          onChange={handleChange}
          onFocus={() => results && setOpen(true)}
          placeholder="Caută parcelă sau UAT…"
          className="w-full rounded-md border bg-background/95 py-1.5 pl-8 pr-8 text-sm shadow-sm backdrop-blur focus:outline-none focus:ring-1 focus:ring-primary"
        />
        {loading && (
          <Loader2 className="absolute right-2 top-1/2 -translate-y-1/2 h-4 w-4 animate-spin text-muted-foreground" />
        )}
      </div>

      {open && results && totalHits > 0 && (
        <div className="absolute left-0 right-0 top-full z-20 mt-1 max-h-96 overflow-y-auto rounded-md border bg-background shadow-lg">
          {results.uats && results.uats.length > 0 && (
            <div>
              <div className="bg-muted/50 px-2 py-1 text-xs font-semibold text-muted-foreground">
                UAT-uri
              </div>
              {results.uats.map((u) => (
                <button
                  key={u.siruta}
                  type="button"
                  onClick={() => {
                    onUatSelect(u);
                    setOpen(false);
                  }}
                  className="flex w-full items-start gap-2 px-2 py-1.5 text-left text-sm hover:bg-muted"
                >
                  <MapPin className="mt-0.5 h-3.5 w-3.5 shrink-0 text-muted-foreground" />
                  <span className="truncate">
                    <span className="font-medium">{u.name}</span>
                    <span className="text-muted-foreground"> · {u.county}</span>
                  </span>
                </button>
              ))}
            </div>
          )}
          {results.features && results.features.length > 0 && (
            <div className="border-t">
              <div className="bg-muted/50 px-2 py-1 text-xs font-semibold text-muted-foreground">
                Parcele
              </div>
              {results.features.map((f) => (
                <button
                  key={f.id}
                  type="button"
                  onClick={() => {
                    onFeatureSelect(f);
                    setOpen(false);
                  }}
                  className="flex w-full items-start gap-2 px-2 py-1.5 text-left text-sm hover:bg-muted"
                >
                  <Hash className="mt-0.5 h-3.5 w-3.5 shrink-0 text-muted-foreground" />
                  <span className="truncate">
                    <span className="font-mono">{f.cadastralRef}</span>
                    {f.areaValue != null && (
                      <span className="ml-2 text-muted-foreground">
                        {f.areaValue.toFixed(0)} m²
                      </span>
                    )}
                  </span>
                </button>
              ))}
            </div>
          )}
        </div>
      )}

      {open && results && totalHits === 0 && !loading && (
        <div className="absolute left-0 right-0 top-full z-20 mt-1 rounded-md border bg-background px-3 py-2 text-sm text-muted-foreground shadow-lg">
          {results.error ? "Eroare la căutare" : "Niciun rezultat"}
        </div>
      )}
    </div>
  );
}
