import { useState } from "react";
import { Input } from "@/components/ui/input";

const AdresseInput = () => {
  const [query, setQuery] = useState("");
  const [suggestions, setSuggestions] = useState<any[]>([]);

  const handleChange = async (e: React.ChangeEvent<HTMLInputElement>) => {
    const value = e.target.value;
    setQuery(value);

    if (value.length >= 3) {
      const response = await fetch(`https://nominatim.openstreetmap.org/search?format=json&q=${encodeURIComponent(value)}&addressdetails=1&limit=5`);
      const data = await response.json();
      setSuggestions(data);
    } else {
      setSuggestions([]);
    }
  };

  const handleSelect = (address: string) => {
    setQuery(address);
    setSuggestions([]);
  };

  return (
    <div className="relative">
      <Input
        placeholder="Straße und Hausnummer"
        value={query}
        onChange={handleChange}
        required
      />
      {suggestions.length > 0 && (
        <div className="absolute z-10 bg-white shadow-md mt-1 rounded-md max-h-60 overflow-y-auto w-full">
          {suggestions.map((suggestion, index) => (
            <div
              key={index}
              onClick={() => handleSelect(suggestion.display_name)}
              className="px-4 py-2 hover:bg-frog-50 cursor-pointer text-sm"
            >
              {suggestion.display_name}
            </div>
          ))}
        </div>
      )}
    </div>
  );
};

export default AdresseInput;
