'use client';

import React, { useState, useEffect } from 'react';
import Link from 'next/link';
import { useRouter, usePathname } from 'next/navigation';
import { motion, AnimatePresence } from 'framer-motion';
import {
  FiSearch, FiMenu, FiBell, FiUser, FiLogOut,
  FiSettings, FiHeart, FiChevronDown,
} from 'react-icons/fi';
import { useAuthStore } from '@/stores/authStore';
import { useProfileStore } from '@/stores/profileStore';
import { useUIStore } from '@/stores/uiStore';
import { useThemeStore } from '@/stores/themeStore';
import { cn } from '@/lib/utils';
import { ROUTES } from '@/lib/constants';
import { moviesApi, seriesApi, channelsApi } from '@/lib/api';

export default function Header() {
  const router = useRouter();
  const pathname = usePathname();
  const { user, logout } = useAuthStore();
  const { activeProfile, selectProfile, watchProgress } = useProfileStore();
  const { toggleSidebar, searchQuery, setSearchQuery } = useUIStore();
  const { theme, setTheme } = useThemeStore();
  const [showProfile, setShowProfile] = useState(false);
  const [showNotifications, setShowNotifications] = useState(false);
  const [hasUnread, setHasUnread] = useState(true);
  const [showSearch, setShowSearch] = useState(false);
  const [localSearch, setLocalSearch] = useState(searchQuery);

  const [searchData, setSearchData] = useState<{
    movies: any[];
    series: any[];
    channels: any[];
  }>({ movies: [], series: [], channels: [] });

  const [suggestions, setSuggestions] = useState<{
    movies: any[];
    series: any[];
    channels: any[];
  }>({ movies: [], series: [], channels: [] });

  const [showSuggestions, setShowSuggestions] = useState(false);

  // Fetch search data once on mount or when search is toggled
  useEffect(() => {
    async function loadSearchData() {
      try {
        const [moviesRes, seriesRes, channelsRes] = await Promise.all([
          moviesApi.getAll(1, 200).catch(() => ({ data: [] })),
          seriesApi.getAll(1, 200).catch(() => ({ data: [] })),
          channelsApi.getAll().catch(() => [])
        ]);
        setSearchData({
          movies: moviesRes?.data || [],
          series: seriesRes?.data || [],
          channels: channelsRes || []
        });
      } catch (err) {
        console.error('Error loading search database:', err);
      }
    }
    if (showSearch) {
      loadSearchData();
    }
  }, [showSearch]);

  // Update suggestions as query changes
  useEffect(() => {
    const q = localSearch.trim().toLowerCase();
    if (q.length < 2) {
      setSuggestions({ movies: [], series: [], channels: [] });
      setShowSuggestions(false);
      return;
    }

    const filteredMovies = searchData.movies
      .filter((m) => m.title?.toLowerCase().includes(q))
      .slice(0, 4);

    const filteredSeries = searchData.series
      .filter((s) => s.title?.toLowerCase().includes(q))
      .slice(0, 4);

    const filteredChannels = searchData.channels
      .filter((c) => c.name?.toLowerCase().includes(q))
      .slice(0, 4);

    setSuggestions({
      movies: filteredMovies,
      series: filteredSeries,
      channels: filteredChannels
    });

    setShowSuggestions(
      filteredMovies.length > 0 ||
      filteredSeries.length > 0 ||
      filteredChannels.length > 0
    );
  }, [localSearch, searchData]);

  const handleSearch = (e: React.FormEvent) => {
    e.preventDefault();
    if (localSearch.trim()) {
      setSearchQuery(localSearch.trim());
      router.push(`/search?q=${encodeURIComponent(localSearch.trim())}`);
      setShowSearch(false);
      setShowSuggestions(false);
    }
  };

  const handleLogout = async () => {
    await logout();
    router.push('/login');
  };

  const navLinks = [
    { href: ROUTES.HOME, label: 'Inicio' },
    { href: ROUTES.TV, label: 'TV en Vivo' },
    { href: ROUTES.MOVIES, label: 'Películas' },
    { href: ROUTES.SERIES, label: 'Series' },
  ];

  return (
    <header className="fixed top-0 left-0 right-0 z-40 transition-all duration-300">
      <div className="bg-dark/80 backdrop-blur-xl border-b border-white/5">
        <div className="flex items-center justify-between h-16 px-4 lg:px-8">
          {/* Left section */}
          <div className="flex items-center gap-4">
            <button
              onClick={toggleSidebar}
              className="lg:hidden p-2 rounded-lg text-white/70 hover:text-white hover:bg-white/10 transition-all"
            >
              <FiMenu size={22} />
            </button>

            <Link href={ROUTES.HOME} className="flex items-center gap-2 group">
              <img
                src="/logo.png"
                alt="Cat Tv"
                className="h-11 w-auto object-contain select-none transition-transform group-hover:scale-105"
              />
            </Link>

            {/* Desktop Nav */}
            <nav className="hidden lg:flex items-center gap-1 ml-6">
              {navLinks.map((link) => (
                <Link
                  key={link.href}
                  href={link.href}
                  className={cn(
                    'px-3 py-2 rounded-lg text-sm font-medium transition-all duration-300',
                    pathname === link.href || pathname?.startsWith(link.href + '/')
                      ? 'text-white bg-white/10'
                      : 'text-white/60 hover:text-white hover:bg-white/5'
                  )}
                >
                  {link.label}
                </Link>
              ))}
            </nav>
          </div>

          {/* Right section */}
          <div className="flex items-center gap-2">
            {/* Search toggle */}
            <AnimatePresence>
              {showSearch && (
                <div className="relative">
                  <motion.form
                    initial={{ width: 0, opacity: 0 }}
                    animate={{ width: 280, opacity: 1 }}
                    exit={{ width: 0, opacity: 0 }}
                    transition={{ duration: 0.3 }}
                    onSubmit={handleSearch}
                    className="relative overflow-visible"
                  >
                    <input
                      type="text"
                      value={localSearch}
                      onChange={(e) => setLocalSearch(e.target.value)}
                      placeholder="Buscar..."
                      autoFocus
                      className="w-full bg-white/5 border border-white/10 rounded-lg px-3 py-1.5 text-sm text-white placeholder-white/30 focus:outline-none focus:border-primary/50"
                      onFocus={() => setShowSuggestions(true)}
                      onBlur={() => {
                        setTimeout(() => setShowSuggestions(false), 200);
                        if (!localSearch) setShowSearch(false);
                      }}
                    />
                  </motion.form>

                  {/* Autocomplete Dropdown Panel */}
                  <AnimatePresence>
                    {showSuggestions && (
                      <motion.div
                        initial={{ opacity: 0, y: 10 }}
                        animate={{ opacity: 1, y: 0 }}
                        exit={{ opacity: 0, y: 10 }}
                        className="absolute right-0 mt-2 w-[340px] bg-dark-200 border border-white/10 rounded-xl shadow-2xl overflow-hidden z-50 p-3 max-h-[420px] overflow-y-auto scrollbar-thin select-none"
                      >
                        {/* Movies Suggestions */}
                        {suggestions.movies.length > 0 && (
                          <div className="mb-4">
                            <span className="text-[10px] font-bold text-white/40 uppercase tracking-widest block mb-2 px-1">Películas</span>
                            <div className="space-y-1">
                              {suggestions.movies.map((m) => (
                                <Link
                                  key={m.id}
                                  href={`/movies/${m.id}`}
                                  className="flex items-center gap-3 p-1.5 hover:bg-white/5 rounded-lg transition-colors text-left"
                                >
                                  <img src={m.posterUrl} alt={m.title} className="w-9 aspect-[2/3] rounded object-cover" />
                                  <div className="overflow-hidden">
                                    <p className="text-xs font-semibold text-white truncate">{m.title}</p>
                                    <p className="text-[10px] text-white/40 mt-0.5">{m.year} · {m.genres?.slice(0, 2).join(', ')}</p>
                                  </div>
                                </Link>
                              ))}
                            </div>
                          </div>
                        )}

                        {/* Series Suggestions */}
                        {suggestions.series.length > 0 && (
                          <div className="mb-4">
                            <span className="text-[10px] font-bold text-white/40 uppercase tracking-widest block mb-2 px-1">Series</span>
                            <div className="space-y-1">
                              {suggestions.series.map((s) => (
                                <Link
                                  key={s.id}
                                  href={`/series/${s.id}`}
                                  className="flex items-center gap-3 p-1.5 hover:bg-white/5 rounded-lg transition-colors text-left"
                                >
                                  <img src={s.posterUrl} alt={s.title} className="w-9 aspect-[2/3] rounded object-cover" />
                                  <div className="overflow-hidden">
                                    <p className="text-xs font-semibold text-white truncate">{s.title}</p>
                                    <p className="text-[10px] text-white/40 mt-0.5">{s.year} · {s.genres?.slice(0, 2).join(', ')}</p>
                                  </div>
                                </Link>
                              ))}
                            </div>
                          </div>
                        )}

                        {/* Channels Suggestions */}
                        {suggestions.channels.length > 0 && (
                          <div>
                            <span className="text-[10px] font-bold text-white/40 uppercase tracking-widest block mb-2 px-1">Canales de TV</span>
                            <div className="space-y-1">
                              {suggestions.channels.map((c) => (
                                <Link
                                  key={c.id}
                                  href={`/tv/${c.id}`}
                                  className="flex items-center gap-3 p-1.5 hover:bg-white/5 rounded-lg transition-colors text-left"
                                >
                                  <img src={c.logoUrl} alt={c.name} className="w-9 aspect-video rounded object-cover bg-black/40" />
                                  <div className="overflow-hidden">
                                    <p className="text-xs font-semibold text-white truncate">{c.name}</p>
                                    {c.currentProgram && <p className="text-[10px] text-primary truncate mt-0.5">Ahora: {c.currentProgram}</p>}
                                  </div>
                                </Link>
                              ))}
                            </div>
                          </div>
                        )}
                      </motion.div>
                    )}
                  </AnimatePresence>
                </div>
              )}
            </AnimatePresence>

            <button
              onClick={() => {
                if (showSearch && localSearch.trim()) {
                  setSearchQuery(localSearch.trim());
                  router.push(`/search?q=${encodeURIComponent(localSearch.trim())}`);
                  setShowSearch(false);
                } else {
                  setShowSearch(!showSearch);
                }
              }}
              className="p-2 rounded-lg text-white/60 hover:text-white hover:bg-white/10 transition-all"
            >
              <FiSearch size={20} />
            </button>

            {/* Notifications */}
            <div className="relative">
              <button
                onClick={() => {
                  setShowNotifications(!showNotifications);
                  setHasUnread(false);
                }}
                className="p-2 rounded-lg text-white/60 hover:text-white hover:bg-white/10 transition-all relative"
              >
                <FiBell size={20} />
                {hasUnread && (
                  <span className="absolute top-1.5 right-1.5 w-2.5 h-2.5 bg-primary rounded-full ring-2 ring-dark-200 animate-pulse" />
                )}
              </button>

              <AnimatePresence>
                {showNotifications && (
                  <>
                    <div
                      className="fixed inset-0 z-40"
                      onClick={() => setShowNotifications(false)}
                    />
                    <motion.div
                      initial={{ opacity: 0, y: -8, scale: 0.96 }}
                      animate={{ opacity: 1, y: 0, scale: 1 }}
                      exit={{ opacity: 0, y: -8, scale: 0.96 }}
                      transition={{ duration: 0.15 }}
                      className="absolute right-0 sm:right-auto sm:-left-32 md:-left-44 mt-2 w-72 bg-dark-200 border border-white/10 rounded-xl shadow-2xl overflow-hidden z-50 p-2 space-y-1.5"
                    >
                      <div className="px-3 py-2 border-b border-white/5 flex justify-between items-center select-none">
                        <span className="text-xs font-bold text-white uppercase tracking-wider">Notificaciones</span>
                        <span className="text-[10px] text-white/40 font-semibold">Recientes</span>
                      </div>
                      
                      <div className="max-h-72 overflow-y-auto space-y-1 scrollbar-none">
                        {/* Welcome Notification */}
                        <div className="p-2.5 hover:bg-white/5 rounded-lg transition-colors text-left flex gap-2.5 items-start">
                          <span className="text-lg select-none">🎉</span>
                          <div>
                            <p className="text-xs font-bold text-white">¡Bienvenido a Cat Tv!</p>
                            <p className="text-[10px] text-white/50 mt-0.5 leading-relaxed font-sans">
                              Hola, {activeProfile?.name || 'usuario'}. Ya puedes disfrutar de todo el contenido del perfil.
                            </p>
                          </div>
                        </div>

                        {/* Subscription Info Notification */}
                        <div className="p-2.5 hover:bg-white/5 rounded-lg transition-colors text-left flex gap-2.5 items-start">
                          <span className="text-lg select-none">📅</span>
                          <div>
                            <p className="text-xs font-bold text-white">Suscripción Activa</p>
                            <p className="text-[10px] text-white/50 mt-0.5 leading-relaxed font-sans">
                              Tu cuenta tiene soporte para {user?.maxDevices || 3} dispositivos. 
                              {user?.expiresAt ? ` Vence el ${new Date(user.expiresAt).toLocaleDateString('es-ES')}.` : ' Vencimiento ilimitado.'}
                            </p>
                          </div>
                        </div>

                        {/* Continue Watching Hint Notification */}
                        {activeProfile && watchProgress[activeProfile.id]?.length > 0 && (
                          <div className="p-2.5 hover:bg-white/5 rounded-lg transition-colors text-left flex gap-2.5 items-start">
                            <span className="text-lg select-none">🍿</span>
                            <div>
                              <p className="text-xs font-bold text-white font-sans">Tienes series o películas pendientes</p>
                              <p className="text-[10px] text-white/50 mt-0.5 leading-relaxed font-sans">
                                Deja las palomitas listas, tienes {watchProgress[activeProfile.id]?.length} títulos listos para continuar.
                              </p>
                            </div>
                          </div>
                        )}
                      </div>
                    </motion.div>
                  </>
                )}
              </AnimatePresence>
            </div>

            {/* Favorites */}
            <Link
              href={ROUTES.FAVORITES}
              className="hidden sm:flex p-2 rounded-lg text-white/60 hover:text-white hover:bg-white/10 transition-all"
            >
              <FiHeart size={20} />
            </Link>

            {/* Profile dropdown */}
            <div className="relative">
              <button
                onClick={() => setShowProfile(!showProfile)}
                className="flex items-center gap-2 p-1.5 rounded-lg hover:bg-white/10 transition-all"
              >
                <div 
                  className="w-8 h-8 rounded-lg flex items-center justify-center text-lg shadow-md shrink-0 overflow-hidden"
                  style={{ background: activeProfile?.avatarColor || 'linear-gradient(135deg, #1e3a8a 0%, #3b82f6 100%)' }}
                >
                  {activeProfile?.avatarUrl ? (
                    <img src={activeProfile.avatarUrl} alt="" className="w-full h-full object-cover" />
                  ) : (
                    activeProfile?.avatarEmoji || user?.username?.charAt(0)?.toUpperCase() || 'U'
                  )}
                </div>
                <span className="hidden sm:block text-xs font-semibold text-white/80 group-hover:text-white truncate max-w-[80px]">
                  {activeProfile?.name || user?.username || 'Usuario'}
                </span>
                <FiChevronDown
                  size={14}
                  className={cn(
                    'hidden sm:block text-white/60 transition-transform',
                    showProfile && 'rotate-180'
                  )}
                />
              </button>

              <AnimatePresence>
                {showProfile && (
                  <>
                    <div
                      className="fixed inset-0 z-40"
                      onClick={() => setShowProfile(false)}
                    />
                    <motion.div
                      initial={{ opacity: 0, y: -8, scale: 0.96 }}
                      animate={{ opacity: 1, y: 0, scale: 1 }}
                      exit={{ opacity: 0, y: -8, scale: 0.96 }}
                      transition={{ duration: 0.15 }}
                      className="absolute right-0 mt-2 w-56 bg-dark-200 border border-white/10 rounded-xl shadow-2xl overflow-hidden z-50"
                    >
                      <div className="p-4 border-b border-white/5 flex items-center gap-3">
                        <div 
                          className="w-10 h-10 rounded-lg flex items-center justify-center text-2xl shadow-md shrink-0 overflow-hidden"
                          style={{ background: activeProfile?.avatarColor || 'linear-gradient(135deg, #1e3a8a 0%, #3b82f6 100%)' }}
                        >
                          {activeProfile?.avatarUrl ? (
                            <img src={activeProfile.avatarUrl} alt="" className="w-full h-full object-cover" />
                          ) : (
                            activeProfile?.avatarEmoji || user?.username?.charAt(0)?.toUpperCase() || 'U'
                          )}
                        </div>
                        <div className="overflow-hidden">
                          <p className="text-sm font-semibold text-white truncate">{activeProfile?.name || 'Usuario'}</p>
                          <p className="text-[10px] text-white/50 truncate mt-0.5">{user?.username || 'Cuenta Principal'}</p>
                        </div>
                      </div>
                      <div className="p-1.5">
                        <button
                          onClick={() => {
                            setShowProfile(false);
                            selectProfile(null);
                          }}
                          className="flex items-center gap-3 px-3 py-2.5 text-sm text-white/70 hover:text-white hover:bg-white/5 rounded-lg transition-all w-full text-left font-medium"
                        >
                          🔄 Cambiar de Perfil
                        </button>
                        <Link
                          href={ROUTES.PROFILE}
                          onClick={() => setShowProfile(false)}
                          className="flex items-center gap-3 px-3 py-2.5 text-sm text-white/70 hover:text-white hover:bg-white/5 rounded-lg transition-all"
                        >
                          <FiUser size={16} /> Mi Cuenta
                        </Link>
                        <Link
                          href={ROUTES.FAVORITES}
                          onClick={() => setShowProfile(false)}
                          className="flex items-center gap-3 px-3 py-2.5 text-sm text-white/70 hover:text-white hover:bg-white/5 rounded-lg transition-all"
                        >
                          <FiHeart size={16} /> Favoritos
                        </Link>
                        {user?.role === 'admin' && (
                          <Link
                            href={ROUTES.ADMIN}
                            onClick={() => setShowProfile(false)}
                            className="flex items-center gap-3 px-3 py-2.5 text-sm text-white/70 hover:text-white hover:bg-white/5 rounded-lg transition-all"
                          >
                            <FiSettings size={16} /> Administración
                          </Link>
                        )}
                      </div>

                      {/* Theme Selector Section */}
                      <div className="p-3 border-t border-white/5 space-y-2">
                        <span className="text-[10px] font-bold text-white/40 uppercase tracking-widest block select-none">Color del Tema</span>
                        <div className="flex justify-between items-center gap-1.5 bg-black/25 p-1 rounded-lg">
                          {[
                            { id: 'rtv', color: '#E6007A', name: 'Cat Neon' },
                            { id: 'netflix', color: '#E50914', name: 'Netflix' },
                            { id: 'spotify', color: '#1DB954', name: 'Spotify' },
                            { id: 'hbo', color: '#7C3AED', name: 'HBO Max' },
                            { id: 'disney', color: '#C19A6B', name: 'Disney+' }
                          ].map((t) => (
                            <button
                              key={t.id}
                              onClick={() => setTheme(t.id as any)}
                              className={cn(
                                "w-6 h-6 rounded-full border transition-all hover:scale-110 relative flex items-center justify-center cursor-pointer",
                                theme === t.id ? "border-white scale-110 shadow-sm" : "border-transparent opacity-65 hover:opacity-100"
                              )}
                              style={{ background: t.color }}
                              title={t.name}
                            >
                              {theme === t.id && (
                                <div className="w-1.5 h-1.5 rounded-full bg-white shadow" />
                              )}
                            </button>
                          ))}
                        </div>
                      </div>
                      <div className="p-1.5 border-t border-white/5">
                        <button
                          onClick={handleLogout}
                          className="flex items-center gap-3 px-3 py-2.5 text-sm text-red-400 hover:text-red-300 hover:bg-red-500/5 rounded-lg transition-all w-full"
                        >
                          <FiLogOut size={16} /> Cerrar Sesión
                        </button>
                      </div>
                    </motion.div>
                  </>
                )}
              </AnimatePresence>
            </div>
          </div>
        </div>
      </div>
    </header>
  );
}
