"use client";

import { useState, useEffect, useRef } from "react";
import { useRouter } from "next/navigation";
import VoiceSearch from "./voice-search";

interface CityResult {
  id: number;
  name: string;
  slug: string;
  country_slug?: string;
  country_name?: string;
}

export default function HeroSearch() {
  const [query, setQuery] = useState("");
  const [focused, setFocused] = useState(false);
  const [cities, setCities] = useState<CityResult[]>([]);
  const [showDropdown, setShowDropdown] = useState(false);
  const [highlightIndex, setHighlightIndex] = useState(-1);
  const debounceRef = useRef<ReturnType<typeof setTimeout> | null>(null);
  const wrapperRef = useRef<HTMLDivElement>(null);
  const router = useRouter();

  // Fetch cities as user types (debounced)
  useEffect(() => {
    if (debounceRef.current) clearTimeout(debounceRef.current);

    const trimmed = query.trim();
    if (trimmed.length < 2) {
      setCities([]);
      setShowDropdown(false);
      return;
    }

    debounceRef.current = setTimeout(async () => {
      try {
        const res = await fetch(
          `/api/search/options/cities/autocomplete?q=${encodeURIComponent(trimmed)}`
        );
        if (res.ok) {
          const data: CityResult[] = await res.json();
          setCities(data);
          setShowDropdown(data.length > 0);
          setHighlightIndex(-1);
        }
      } catch {
        // ignore fetch errors
      }
    }, 250);

    return () => {
      if (debounceRef.current) clearTimeout(debounceRef.current);
    };
  }, [query]);

  // Close dropdown on outside click
  useEffect(() => {
    function handleClickOutside(e: MouseEvent) {
      if (wrapperRef.current && !wrapperRef.current.contains(e.target as Node)) {
        setShowDropdown(false);
      }
    }
    document.addEventListener("mousedown", handleClickOutside);
    return () => document.removeEventListener("mousedown", handleClickOutside);
  }, []);

  const handleSubmit = (e: React.FormEvent) => {
    e.preventDefault();

    // If a city is highlighted in dropdown, navigate to it
    if (highlightIndex >= 0 && highlightIndex < cities.length) {
      navigateToCity(cities[highlightIndex]);
      return;
    }

    const trimmed = query.trim();
    if (!trimmed) return;
    router.push(`/search/results?keyword=${encodeURIComponent(trimmed)}`);
  };

  const navigateToCity = (city: CityResult) => {
    setShowDropdown(false);
    if (city.country_slug) {
      router.push(`/escorts/${city.country_slug}/${city.slug}`);
    } else {
      router.push(`/search/results?city=${city.id}`);
    }
  };

  const handleKeyDown = (e: React.KeyboardEvent) => {
    if (!showDropdown || cities.length === 0) return;

    if (e.key === "ArrowDown") {
      e.preventDefault();
      setHighlightIndex((prev) => (prev < cities.length - 1 ? prev + 1 : 0));
    } else if (e.key === "ArrowUp") {
      e.preventDefault();
      setHighlightIndex((prev) => (prev > 0 ? prev - 1 : cities.length - 1));
    } else if (e.key === "Escape") {
      setShowDropdown(false);
    }
  };

  return (
    <form onSubmit={handleSubmit} className="max-w-xl mx-auto mt-8">
      <div ref={wrapperRef} className="relative">
        <div
          className={`flex items-center rounded-xl border-2 transition-all duration-200 bg-surface/80 backdrop-blur-sm ${
            focused
              ? "border-gold shadow-lg shadow-gold/10"
              : "border-white/10 hover:border-white/20"
          }`}
        >
          <div className="pl-4 text-text-muted">
            <svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
              <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M21 21l-6-6m2-5a7 7 0 11-14 0 7 7 0 0114 0z" />
            </svg>
          </div>
          <input
            type="text"
            value={query}
            onChange={(e) => setQuery(e.target.value)}
            onFocus={() => setFocused(true)}
            onBlur={() => setFocused(false)}
            onKeyDown={handleKeyDown}
            placeholder="Search by name or city..."
            className="flex-1 bg-transparent px-4 py-3.5 text-white placeholder-text-muted outline-none text-sm"
          />
          <button
            type="submit"
            className="bg-gold hover:bg-gold-light text-black font-semibold px-6 py-2.5 rounded-lg mr-1.5 transition-all duration-200 text-sm whitespace-nowrap"
          >
            Search
          </button>
          <div className="mr-1.5">
            <VoiceSearch />
          </div>
        </div>

        {/* City autocomplete dropdown */}
        {showDropdown && cities.length > 0 && (
          <div className="absolute z-50 mt-1 w-full bg-surface border border-white/10 rounded-xl shadow-xl overflow-hidden">
            <div className="px-3 py-1.5 text-xs text-text-muted border-b border-white/5">
              Cities
            </div>
            {cities.map((city, i) => (
              <button
                key={city.id}
                type="button"
                onMouseDown={(e) => {
                  e.preventDefault();
                  navigateToCity(city);
                }}
                onMouseEnter={() => setHighlightIndex(i)}
                className={`w-full text-left px-4 py-2.5 flex items-center gap-3 transition-colors ${
                  i === highlightIndex
                    ? "bg-gold/10 text-white"
                    : "text-text-muted hover:bg-surface-light hover:text-white"
                }`}
              >
                <svg className="w-4 h-4 shrink-0" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                  <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M17.657 16.657L13.414 20.9a1.998 1.998 0 01-2.827 0l-4.244-4.243a8 8 0 1111.314 0z" />
                  <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M15 11a3 3 0 11-6 0 3 3 0 016 0z" />
                </svg>
                <div>
                  <span className="text-sm font-medium">{city.name}</span>
                  {city.country_name && (
                    <span className="text-xs text-text-muted ml-2">{city.country_name}</span>
                  )}
                </div>
              </button>
            ))}
          </div>
        )}
      </div>
    </form>
  );
}
