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

const LocationAutocomplete = ({ label, value, onChange, placeholder, icon = "location" }) => {
  const [query, setQuery] = useState(value || "");
  const [suggestions, setSuggestions] = useState([]);
  const [isLoading, setIsLoading] = useState(false);
  const [showDropdown, setShowDropdown] = useState(false);
  const dropdownRef = useRef(null);

  const fetchSuggestions = async (searchText) => {
    if (searchText.length < 3) {
      setSuggestions([]);
      return;
    }

    setIsLoading(true);
    try {
      const response = await fetch(`https://photon.komoot.io/api?q=${encodeURIComponent(searchText)}&limit=5`);
      const data = await response.json();
      
      const results = data.features.map(feature => {
        const { name, city, state, country } = feature.properties;
        const mainText = name || city;
        const secondaryText = [city, state, country].filter(Boolean).join(", ");
        return {
          id: feature.geometry.coordinates.join(","),
          mainText,
          secondaryText,
          description: `${mainText}${secondaryText ? `, ${secondaryText}` : ""}`
        };
      });
      
      setSuggestions(results);
      setShowDropdown(results.length > 0);
    } catch (error) {
      console.error("Error fetching location suggestions:", error);
    } finally {
      setIsLoading(false);
    }
  };

  const debouncedFetch = useRef(debounce(fetchSuggestions, 500)).current;

  useEffect(() => {
    if (query !== value) {
      debouncedFetch(query);
    }
  }, [query]);

  useEffect(() => {
    const handleClickOutside = (event) => {
      if (dropdownRef.current && !dropdownRef.current.contains(event.target)) {
        setShowDropdown(false);
      }
    };
    document.addEventListener("mousedown", handleClickOutside);
    return () => document.removeEventListener("mousedown", handleClickOutside);
  }, []);

  const handleSelect = (suggestion) => {
    setQuery(suggestion.description);
    onChange(suggestion.description);
    setShowDropdown(false);
  };

  return (
    <div className="flex-1 min-w-[200px] px-4 py-3 relative" ref={dropdownRef}>
      <div className="flex items-center gap-2">
        <MapPin className={`w-4 h-4 ${icon === 'location' ? 'text-red-500' : 'text-primary-600'} flex-shrink-0`} />
        <div className="flex-1">
          <p className="text-[11px] text-badge-text font-medium leading-none mb-1">{label}</p>
          <div className="relative">
            <input
              type="text"
              value={query}
              onChange={(e) => setQuery(e.target.value)}
              onFocus={() => query.length >= 3 && setShowDropdown(true)}
              placeholder={placeholder}
              className="text-sm font-semibold text-dark-900 placeholder:text-gray-400 bg-transparent border-none outline-none w-full"
            />
            {isLoading && (
              <Loader2 className="absolute right-0 top-1/2 -translate-y-1/2 w-3 h-3 text-gray-400 animate-spin" />
            )}
          </div>
        </div>
      </div>

      {/* Dropdown Suggestions */}
      {showDropdown && suggestions.length > 0 && (
        <div className="absolute left-0 right-0 top-full mt-2 bg-white/95 backdrop-blur-md rounded-xl shadow-2xl border border-gray-100 z-50 overflow-hidden animate-fadeInUp">
          {suggestions.map((suggestion, index) => (
            <button
              key={index}
              onClick={() => handleSelect(suggestion)}
              className="w-full text-left px-5 py-3 hover:bg-gray-50 transition-colors flex flex-col border-b border-gray-50 last:border-none"
            >
              <span className="text-sm font-bold text-dark-900">{suggestion.mainText}</span>
              <span className="text-[11px] text-gray-500 truncate">{suggestion.secondaryText}</span>
            </button>
          ))}
        </div>
      )}
    </div>
  );
};

export default LocationAutocomplete;
