"use client";
import { useState, useEffect, useRef } from "react";
import { Search, Play, Users, Folder, Crown, BadgeCheck } from "lucide-react";
import Link from "next/link";
import { useRouter } from "next/navigation";

export function LiveSearch({ onResultClick }: { onResultClick?: () => void }) {
  const [query, setQuery] = useState("");
  const [results, setResults] = useState<{ videos: any[], categories: any[], channels: any[] } | null>(null);
  const [isOpen, setIsOpen] = useState(false);
  const [loading, setLoading] = useState(false);
  const wrapperRef = useRef<HTMLDivElement>(null);
  const inputRef = useRef<HTMLInputElement>(null);
  const router = useRouter();

  useEffect(() => {
    // Focus input automatically when component mounts inside modal
    inputRef.current?.focus();
  }, []);

  useEffect(() => {
    const handleClickOutside = (e: MouseEvent) => {
      if (wrapperRef.current && !wrapperRef.current.contains(e.target as Node)) {
        setIsOpen(false);
      }
    };
    document.addEventListener("mousedown", handleClickOutside);
    return () => document.removeEventListener("mousedown", handleClickOutside);
  }, []);

  useEffect(() => {
    if (query.trim().length < 2) {
      setResults(null);
      return;
    }

    const timer = setTimeout(async () => {
      setLoading(true);
      try {
        const res = await fetch(`/api/search?q=${encodeURIComponent(query)}`);
        const data = await res.json();
        setResults(data);
        setIsOpen(true);
      } catch (err) {
        console.error(err);
      } finally {
        setLoading(false);
      }
    }, 300); // debounce

    return () => clearTimeout(timer);
  }, [query]);

  const handleSearch = () => {
    if (query.trim()) {
      // Sauvegarde la recherche pour personnaliser le feed
      try {
        const existing: string[] = JSON.parse(localStorage.getItem("recentSearches") || "[]");
        const keywords = query.trim().toLowerCase().split(/\s+/).filter(Boolean);
        const updated = [...keywords, ...existing].slice(0, 50);
        localStorage.setItem("recentSearches", JSON.stringify(updated));
      } catch {}
      setIsOpen(false);
      if (onResultClick) onResultClick();
      router.push(`/videos?q=${encodeURIComponent(query)}`);
    }
  };


  return (
    <div className="relative flex items-center w-full" ref={wrapperRef}>
      <div className="flex items-center w-full h-[40px] bg-[#12080b] border border-white/25 hover:border-white/45 focus-within:border-[#e05a68] focus-within:shadow-[0_0_20px_rgba(224,90,104,0.35)] rounded-full overflow-hidden transition-all duration-200">
        <input
          ref={inputRef}
          value={query}
          onChange={e => setQuery(e.target.value)}
          onKeyDown={e => { if (e.key === 'Enter') handleSearch(); }}
          placeholder="Rechercher une vidéo..."
          className="flex-1 h-full px-4 text-sm bg-transparent text-white placeholder-[#888888] focus:outline-none"
        />
        <button
          className="h-full px-4 flex items-center justify-center text-white/70 hover:text-black hover:bg-[#e05a68] border-l border-white/20 transition-all flex-shrink-0 cursor-pointer"
          onClick={handleSearch}
          title="Rechercher"
        >
          <Search size={17} />
        </button>
      </div>

      {isOpen && results && (
        <div className="absolute top-14 left-0 right-0 w-full sm:w-[450px] max-h-[70vh] overflow-y-auto bg-[#0a0a0f]/95 backdrop-blur-xl border border-[#e05a68]/20 rounded-2xl shadow-[0_10px_40px_rgba(224,90,104,0.15)] z-[100] animate-in fade-in slide-in-from-top-4 duration-300 custom-scrollbar">
          
          {loading && <div className="p-6 text-center text-sm text-[#e05a68] animate-pulse font-medium">Recherche en cours...</div>}

          {!loading && results.channels.length > 0 && (
            <div className="border-b border-[#2e1217] pb-2">
              <div className="px-5 py-3 text-[10px] font-black text-[#e05a68] tracking-wider flex items-center gap-2 uppercase">
                <Users size={14} /> Chaînes
              </div>
              {results.channels.map(channel => (
                <Link key={channel.id} href={`/channel/${channel.id}`} onClick={() => { setIsOpen(false); if (onResultClick) onResultClick(); }} className="flex items-center gap-3 px-5 py-2.5 hover:bg-[#e05a68]/10 transition-colors group">
                  <div className="w-10 h-10 rounded-full bg-[#12080b] border border-[#2e1217] overflow-hidden shrink-0 group-hover:border-[#e05a68]/50 transition-colors">
                    {channel.image ? <img src={channel.image} className="w-full h-full object-cover" /> : <div className="w-full h-full flex items-center justify-center font-bold text-[#aaaaaa] group-hover:text-white transition-colors">{channel.name[0]}</div>}
                  </div>
                  <div className="flex items-center gap-1.5">
                    <span className="font-bold text-sm text-white group-hover:text-[#e05a68] transition-colors">{channel.name}</span>
                    {channel.isVerified && <BadgeCheck size={14} className="text-[#e05a68]" fill="currentColor" />}
                  </div>
                </Link>
              ))}
            </div>
          )}

          {!loading && results.categories.length > 0 && (
            <div className="border-b border-[#2e1217] pb-2 pt-2">
              <div className="px-5 py-3 text-[10px] font-black text-[#e05a68] tracking-wider flex items-center gap-2 uppercase">
                <Folder size={14} /> Catégories
              </div>
              {results.categories.map(cat => (
                <Link key={cat.id} href={`/videos?cat=${cat.id}`} onClick={() => { setIsOpen(false); if (onResultClick) onResultClick(); }} className="block px-5 py-2.5 hover:bg-[#e05a68]/10 transition-colors text-sm font-bold text-white group">
                  <span className="group-hover:text-[#e05a68] transition-colors">{cat.name}</span>
                </Link>
              ))}
            </div>
          )}

          {!loading && results.videos.length > 0 && (
            <div className="pt-2 pb-2">
              <div className="px-5 py-3 text-[10px] font-black text-[#e05a68] tracking-wider flex items-center gap-2 uppercase">
                <Play size={14} /> Vidéos
              </div>
              {results.videos.map(video => (
                <Link key={video.id} href={`/video/${video.id}`} onClick={() => { setIsOpen(false); if (onResultClick) onResultClick(); }} className="flex items-start gap-4 px-5 py-2.5 hover:bg-[#e05a68]/10 transition-colors group">
                  <div className="w-28 aspect-video bg-[#12080b] border border-[#2e1217] rounded-lg shrink-0 overflow-hidden relative group-hover:border-[#e05a68]/50 transition-colors">
                    {video.thumbnailUrl && <img src={video.thumbnailUrl} className="w-full h-full object-cover" />}
                    {video.isPremium && <Crown size={12} className="absolute top-1.5 right-1.5 text-yellow-500 bg-black/50 p-0.5 rounded-full backdrop-blur-sm" />}
                  </div>
                  <div className="font-bold text-sm line-clamp-2 leading-snug text-[#cccccc] group-hover:text-white transition-colors flex-1 mt-0.5">
                    {video.title}
                  </div>
                </Link>
              ))}
            </div>
          )}

          {!loading && results.videos.length === 0 && results.channels.length === 0 && results.categories.length === 0 && (
            <div className="p-8 text-center text-sm font-medium text-[#aaaaaa]">Aucun résultat trouvé pour "<span className="text-white">{query}</span>"</div>
          )}
        </div>
      )}
    </div>
  );
}

