"use client";

import { useState, useRef, useEffect, useCallback } from "react";
import { Search, X, Loader2, TrendingUp, ChevronRight } from "lucide-react";
import { useRouter } from "next/navigation";
import Image from "next/image";
import { motion, AnimatePresence } from "framer-motion";
import { fetchSuggestions } from "@/lib/api";
import type { Car } from "@/lib/types";
import { formatPrice } from "@/lib/utils";
import { resolveCarHeroImage } from "@/lib/carImage";
import BrandLogo from "@/components/brand/BrandLogo";
import BodyTypeSilhouette from "@/components/ui/BodyTypeSilhouette";

interface Props {
  placeholder?: string;
  initialQuery?: string;
  onSearch?: (q: string) => void;
  className?: string;
}

// Popular quick-search shortcuts shown when the box is empty
const QUICK_SEARCHES = [
  "Hyundai Creta", "Tata Nexon", "Maruti Swift", "Kia Seltos",
];

export default function SearchBar({
  placeholder = "Search cars by brand or model…",
  initialQuery = "",
  onSearch,
  className,
}: Props) {
  const router = useRouter();
  const [query, setQuery]     = useState(initialQuery);
  const [results, setResults] = useState<Car[]>([]);
  const [loading, setLoading] = useState(false);
  const [open, setOpen]       = useState(false);
  const [focused, setFocused] = useState(false);
  const wrapRef    = useRef<HTMLDivElement>(null);
  const inputRef   = useRef<HTMLInputElement>(null);
  const debounceRef = useRef<NodeJS.Timeout>();

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

  const fetchResults = useCallback(async (q: string) => {
    if (q.length < 2) { setResults([]); return; }
    setLoading(true);
    try {
      const res = await fetchSuggestions(q);
      setResults(res.suggestions ?? []);
      if ((res.suggestions ?? []).length > 0) setOpen(true);
    } catch {
      setResults([]);
    } finally {
      setLoading(false);
    }
  }, []);

  function handleChange(e: React.ChangeEvent<HTMLInputElement>) {
    const v = e.target.value;
    setQuery(v);
    clearTimeout(debounceRef.current);
    if (v.length < 2) { setResults([]); setOpen(false); return; }
    debounceRef.current = setTimeout(() => fetchResults(v), 280);
  }

  function handleSubmit(e?: React.FormEvent) {
    e?.preventDefault();
    setOpen(false);
    setFocused(false);
    if (onSearch) { onSearch(query); return; }
    if (query.trim()) router.push(`/cars?search=${encodeURIComponent(query.trim())}`);
  }

  function handleClear() {
    setQuery("");
    setResults([]);
    setOpen(false);
    inputRef.current?.focus();
    if (onSearch) onSearch("");
  }

  function handleSelect(car: Car) {
    setOpen(false);
    setFocused(false);
    router.push(`/cars/${car.id}`);
  }

  function handleQuick(term: string) {
    setQuery(term);
    setOpen(false);
    setFocused(false);
    if (onSearch) { onSearch(term); return; }
    router.push(`/cars?search=${encodeURIComponent(term)}`);
  }

  const showQuickLinks = focused && !query && !loading;

  return (
    <div ref={wrapRef} className={`relative w-full ${className ?? ""}`}>
      {/* combobox wrapper carries the aria-expanded/controls attributes;
          input retains only aria-label + aria-autocomplete (valid on textbox) */}
      <div
        role="combobox"
        aria-expanded={open}
        aria-controls="search-dropdown"
        aria-haspopup="listbox"
      >
      <form onSubmit={handleSubmit} className="flex items-center">
        {/* Search icon */}
        <Search
          className="w-4 h-4 text-gray-400 ml-3 shrink-0"
          aria-hidden="true"
        />

        {/* Input */}
        <input
          ref={inputRef}
          type="search"
          value={query}
          onChange={handleChange}
          onFocus={() => setFocused(true)}
          placeholder={placeholder}
          aria-label="Search cars"
          aria-autocomplete="list"
          autoComplete="off"
          className="flex-1 px-3 py-2.5 text-sm text-gray-800 placeholder-gray-400 bg-transparent outline-none"
        />

        {/* Spinner */}
        {loading && (
          <Loader2 className="w-4 h-4 text-gray-400 mr-2 animate-spin shrink-0" aria-hidden="true" />
        )}

        {/* Clear button */}
        {!loading && query && (
          <button
            type="button"
            onClick={handleClear}
            aria-label="Clear search"
            className="p-1.5 mr-1 text-gray-400 hover:text-gray-600 rounded-lg hover:bg-gray-100 transition-colors focus:outline-none focus:ring-2 focus:ring-gray-300"
          >
            <X className="w-3.5 h-3.5" aria-hidden="true" />
          </button>
        )}

        {/* Search button */}
        <button
          type="submit"
          aria-label="Submit search"
          className="bg-gradient-to-r from-blue-600 to-cyan-500 text-white text-sm font-bold px-5 py-2.5 rounded-r-xl hover:from-blue-700 hover:to-cyan-600 active:scale-95 transition-all shrink-0 h-full focus:outline-none focus:ring-2 focus:ring-blue-400"
        >
          Search
        </button>
      </form>

      {/* ── Dropdown ─────────────────────────────────────────────────────── */}
      <AnimatePresence>
        {(open || showQuickLinks) && (
          <motion.div
            id="search-dropdown"
            role="listbox"
            aria-label="Search suggestions"
            initial={{ opacity: 0, y: -8, scale: 0.98 }}
            animate={{ opacity: 1, y: 0, scale: 1 }}
            exit={{ opacity: 0, y: -8, scale: 0.98 }}
            transition={{ duration: 0.15 }}
            className="absolute top-full left-0 right-0 mt-2 bg-white/95 backdrop-blur-xl border border-gray-200/70 rounded-[20px] shadow-[0_20px_60px_rgba(0,0,0,0.12)] z-[9999] overflow-hidden"
          >
            {/* Quick searches (when input is empty) */}
            {showQuickLinks && (
              <div className="px-4 py-3 border-b border-gray-100">
                <div className="flex items-center gap-2 mb-2.5">
                  <TrendingUp className="w-3.5 h-3.5 text-blue-500" aria-hidden="true" />
                  <span className="text-[10px] uppercase tracking-[0.15em] text-gray-400 font-black">
                    Popular Searches
                  </span>
                </div>
                <div className="flex flex-wrap gap-1.5">
                  {QUICK_SEARCHES.map((term) => (
                    <button
                      key={term}
                      type="button"
                      onClick={() => handleQuick(term)}
                      className="px-3 py-1.5 bg-gray-100 hover:bg-blue-50 hover:text-blue-600 text-xs font-semibold text-gray-700 rounded-xl transition-colors focus:outline-none focus:ring-2 focus:ring-blue-400"
                    >
                      {term}
                    </button>
                  ))}
                </div>
              </div>
            )}

            {/* Car suggestion rows */}
            {results.map((car, i) => {
              const heroSrc = resolveCarHeroImage(car);
              return (
                <motion.button
                  key={car.id}
                  role="option"
                  aria-selected={false}
                  type="button"
                  initial={{ opacity: 0, x: -8 }}
                  animate={{ opacity: 1, x: 0 }}
                  transition={{ delay: i * 0.04 }}
                  onClick={() => handleSelect(car)}
                  className="w-full flex items-center gap-3 px-4 py-3 hover:bg-blue-50/60 transition-colors text-left border-b border-gray-100/60 last:border-0 group focus:outline-none focus:bg-blue-50"
                >
                  {/* Car thumbnail / silhouette */}
                  <div className="w-16 h-11 relative rounded-xl overflow-hidden bg-gradient-to-br from-gray-100 to-gray-50 shrink-0 border border-gray-100">
                    {heroSrc ? (
                      <Image
                        src={heroSrc}
                        alt={car.name}
                        fill
                        className="object-cover"
                        sizes="64px"
                      />
                    ) : (
                      <div className="absolute inset-0 flex items-center justify-center p-2">
                        <BodyTypeSilhouette
                          type={car.bodyType}
                          className="w-full h-full text-gray-300"
                        />
                      </div>
                    )}
                  </div>

                  {/* Info */}
                  <div className="flex-1 min-w-0">
                    <p className="text-sm font-bold text-gray-900 truncate group-hover:text-blue-600 transition-colors">
                      {car.name}
                    </p>
                    <div className="flex items-center gap-2 mt-0.5">
                      {/* Brand logo micro */}
                      <BrandLogo brand={car.brand} size={14} showWhiteBg={false} />
                      <p className="text-xs text-gray-500 truncate">
                        {car.brand}
                        {car.priceMin ? ` · ${formatPrice(car.priceMin)}` : ""}
                      </p>
                    </div>
                  </div>

                  <ChevronRight
                    className="w-4 h-4 text-gray-300 group-hover:text-blue-400 transition-colors shrink-0"
                    aria-hidden="true"
                  />
                </motion.button>
              );
            })}

            {/* "See all results" footer */}
            {query && results.length > 0 && (
              <button
                type="button"
                onClick={() => handleSubmit()}
                className="w-full px-4 py-3.5 flex items-center gap-2 text-xs font-bold text-blue-600 hover:bg-blue-50 transition-colors border-t border-gray-100 focus:outline-none"
              >
                <Search className="w-3.5 h-3.5" aria-hidden="true" />
                See all results for &ldquo;{query}&rdquo;
              </button>
            )}

            {/* No results */}
            {query.length >= 2 && !loading && results.length === 0 && (
              <div className="px-4 py-6 text-center">
                <div className="w-12 h-12 rounded-2xl bg-gray-100 flex items-center justify-center mx-auto mb-3">
                  <Search className="w-5 h-5 text-gray-400" aria-hidden="true" />
                </div>
                <p className="text-sm font-semibold text-gray-600 mb-1">No results for &ldquo;{query}&rdquo;</p>
                <p className="text-xs text-gray-400">Try a different brand or model name</p>
              </div>
            )}
          </motion.div>
        )}
      </AnimatePresence>
      </div>{/* end role="combobox" */}
    </div>
  );
}
