"use client";

import { useState, useEffect, useRef } from "react";
import { useRouter } from "next/navigation";
import { Search, ChevronDown, Menu, Loader2, Store, ArrowRight } from "lucide-react";
import Link from "next/link";

export function SearchBar({ mobile = false, variant = "header" }: { mobile?: boolean, variant?: "header" | "hero" }) {
  const router = useRouter();
  const [searchTerm, setSearchTerm] = useState("");
  const [suggestions, setSuggestions] = useState<Record<string, any>[]>([]);
  const [isLoading, setIsLoading] = useState(false);
  const [showDropdown, setShowDropdown] = useState(false);
  const dropdownRef = useRef<HTMLDivElement>(null);

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

  useEffect(() => {
    const fetchSuggestions = async () => {
      if (!searchTerm.trim() || searchTerm.trim().length < 2) {
        setSuggestions([]);
        return;
      }

      setIsLoading(true);
      try {
        const res = await fetch(`/api/search-suggestions?q=${encodeURIComponent(searchTerm)}`);
        if (res.ok) {
          const data = await res.json();
          setSuggestions(data.products || []);
        }
      } catch (error) {
        console.error("Error fetching suggestions:", error);
      } finally {
        setIsLoading(false);
      }
    };

    const debounceTimer = setTimeout(() => {
      if (showDropdown) {
        fetchSuggestions();
      }
    }, 300);

    return () => clearTimeout(debounceTimer);
  }, [searchTerm, showDropdown]);

  const handleSearch = (e?: React.FormEvent) => {
    if (e) e.preventDefault();
    if (searchTerm.trim()) {
      setShowDropdown(false);
      router.push(`/busca?q=${encodeURIComponent(searchTerm)}`);
    }
  };

  const handleFocus = () => {
    setShowDropdown(true);
  };

  return (
    <div className={`relative w-full ${variant === "hero" ? "" : mobile ? "" : "flex-1 max-w-2xl mx-8"}`} ref={dropdownRef}>
      {variant === "hero" ? (
        <form onSubmit={handleSearch} className="flex items-center bg-white rounded-full border border-gray-200 shadow-sm p-2 focus-within:border-violet-400 focus-within:ring-2 focus-within:ring-violet-100 transition-all relative z-20">
          <div className="pl-4 pr-2 text-gray-400">
            <Search className="w-5 h-5" />
          </div>
          <input 
            type="text" 
            value={searchTerm}
            onChange={(e) => setSearchTerm(e.target.value)}
            onFocus={handleFocus}
            placeholder="O que você está procurando?" 
            className="flex-1 bg-transparent py-3 px-2 text-gray-700 outline-none placeholder:text-gray-400"
            autoComplete="off"
          />
          <button type="submit" className="bg-violet-600 text-white w-12 h-12 rounded-full flex items-center justify-center hover:bg-violet-700 transition-colors shadow-md">
            <ArrowRight className="w-5 h-5" />
          </button>
        </form>
      ) : (
        <form 
          onSubmit={handleSearch} 
          className="flex w-full bg-gray-50 rounded-full border border-gray-200 focus-within:border-violet-400 focus-within:ring-2 focus-within:ring-violet-100 transition-all relative z-20"
        >
          {!mobile && (
            <button type="button" className="flex items-center gap-2 px-4 py-2 text-sm text-gray-600 font-medium border-r border-gray-200 hover:text-gray-900">
              <Menu className="w-4 h-4" />
              Todas as categorias
              <ChevronDown className="w-4 h-4" />
            </button>
          )}
          <input 
            type="text" 
            value={searchTerm}
            onChange={(e) => setSearchTerm(e.target.value)}
            onFocus={handleFocus}
            placeholder={mobile ? "O que você está procurando?" : "Buscar produtos, lojas e coleções..."}
            className={`flex-1 bg-transparent px-4 ${mobile ? "py-3" : "py-2"} text-sm outline-none placeholder:text-gray-400`}
            autoComplete="off"
          />
          <button type="submit" className="bg-violet-600 text-white p-2 m-1 rounded-full hover:bg-violet-700 transition-colors">
            <Search className="w-5 h-5" />
          </button>
        </form>
      )}

      {/* Autocomplete Dropdown */}
      {showDropdown && searchTerm.trim().length >= 2 && (
        <div className="absolute top-full left-0 right-0 mt-2 bg-white rounded-2xl shadow-xl border border-gray-100 overflow-hidden z-50 flex flex-col max-h-[70vh]">
          <div className="overflow-y-auto p-2">
            {isLoading ? (
              <div className="flex items-center justify-center p-6 text-gray-400">
                <Loader2 className="w-6 h-6 animate-spin" />
              </div>
            ) : suggestions.length > 0 ? (
              <div className="flex flex-col gap-1">
                {suggestions.map((product) => (
                  <Link
                    key={product.id}
                    href={`/produtos/${product.id}`}
                    onClick={() => setShowDropdown(false)}
                    className="flex items-center gap-3 p-2 hover:bg-gray-50 rounded-xl transition-colors group"
                  >
                    <div className="w-12 h-12 bg-gray-100 rounded-lg overflow-hidden flex-shrink-0">
                      {product.image_url ? (
                        <img src={product.image_url} alt={product.name} className="w-full h-full object-cover" />
                      ) : (
                        <div className="w-full h-full flex items-center justify-center text-gray-400">
                          <Search className="w-4 h-4" />
                        </div>
                      )}
                    </div>
                    <div className="flex-1 min-w-0">
                      <p className="text-sm font-medium text-gray-900 truncate group-hover:text-violet-600 transition-colors">
                        {product.name}
                      </p>
                      <div className="flex items-center gap-1 mt-0.5 text-xs text-gray-500">
                        <Store className="w-3 h-3" />
                        <span className="truncate">{product.store_name}</span>
                      </div>
                    </div>
                    <div className="font-bold text-violet-600 text-sm whitespace-nowrap pl-2">
                      R$ {product.price?.toLocaleString('pt-BR', { minimumFractionDigits: 2, maximumFractionDigits: 2 })}
                    </div>
                  </Link>
                ))}
              </div>
            ) : (
              <div className="p-6 text-center text-gray-500 text-sm">
                Nenhum resultado encontrado para &quot;{searchTerm}&quot;
              </div>
            )}
          </div>
          
          {/* Ver todos os resultados */}
          <div className="p-2 border-t border-gray-100 bg-gray-50/50">
            <button 
              onClick={() => handleSearch()}
              className="w-full py-2.5 px-4 bg-white border border-gray-200 rounded-xl text-sm font-bold text-violet-600 hover:bg-violet-50 hover:border-violet-200 transition-all flex items-center justify-center gap-2"
            >
              <Search className="w-4 h-4" />
              Ver todos os resultados
            </button>
          </div>
        </div>
      )}
    </div>
  );
}
