"use client";

import { useState, useEffect, useRef } from "react";
import { Search, Crown, User, Menu, X, Bell, Home, Film, Tv, Music, Sparkles } from "lucide-react";
import { useAppStore, useAuthStore, type ViewName } from "@/lib/store";
import { useApi } from "@/lib/api";
import { cn } from "@/lib/utils";

const NAV_ITEMS: { view: ViewName; label: string; icon: any }[] = [
  { view: "home", label: "خانه", icon: Home },
  { view: "movies", label: "فیلم", icon: Film },
  { view: "series", label: "سریال", icon: Film },
  { view: "live", label: "تلویزیون زنده", icon: Tv },
  { view: "music", label: "موزیک", icon: Music },
  { view: "ai-center", label: "هوش مصنوعی", icon: Sparkles },
];

export function Navbar() {
  const navigate = useAppStore((s) => s.navigate);
  const search = useAppStore((s) => s.search);
  const currentView = useAppStore((s) => s.view);
  const user = useAuthStore((s) => s.user);
  const [scrolled, setScrolled] = useState(false);
  const [searchOpen, setSearchOpen] = useState(false);
  const [q, setQ] = useState("");
  const inputRef = useRef<HTMLInputElement>(null);

  useEffect(() => {
    const onScroll = () => setScrolled(window.scrollY > 30);
    window.addEventListener("scroll", onScroll);
    return () => window.removeEventListener("scroll", onScroll);
  }, []);

  // Fetch search suggestions (recent) when opening
  const { data: searchData } = useApi<{ suggestion: string[] }>(searchOpen ? "/api/search" : null);
  const suggestions = searchData?.suggestion ?? [];

  useEffect(() => {
    if (searchOpen) inputRef.current?.focus();
  }, [searchOpen]);

  const submitSearch = (e: React.FormEvent) => {
    e.preventDefault();
    if (q.trim()) {
      search(q.trim());
      setSearchOpen(false);
      setQ("");
    }
  };

  return (
    <header
      className={cn(
        "fixed top-0 inset-x-0 z-50 transition-all duration-300",
        scrolled ? "glass-strong shadow-lg" : "bg-gradient-to-b from-black/80 to-transparent",
      )}
    >
      <div className="flex items-center gap-4 px-4 md:px-8 h-16">
        {/* Logo */}
        <button
          onClick={() => navigate("home")}
          className="flex items-center gap-2 shrink-0"
          aria-label="PeepBox خانه"
        >
          <div className="flex h-9 w-9 items-center justify-center rounded-xl bg-gradient-brand shadow-glow">
            <PlayIcon />
          </div>
          <span className="text-xl font-black tracking-tight">
            <span className="text-gradient">PEEP</span>
            <span className="text-foreground">BOX</span>
          </span>
        </button>

        {/* Desktop nav */}
        <nav className="hidden md:flex items-center gap-1 mr-2">
          {NAV_ITEMS.map((item) => (
            <button
              key={item.view}
              onClick={() => navigate(item.view)}
              className={cn(
                "px-3 py-2 rounded-lg text-sm font-medium transition",
                currentView === item.view
                  ? "text-white bg-primary/20"
                  : "text-muted-foreground hover:text-white hover:bg-white/5",
              )}
            >
              {item.label}
            </button>
          ))}
        </nav>

        <div className="flex-1" />

        {/* Search */}
        <div className="relative flex items-center">
          {searchOpen ? (
            <form onSubmit={submitSearch} className="flex items-center">
              <div className="flex items-center glass rounded-full px-3 py-1.5 w-[180px] md:w-[280px]">
                <Search className="h-4 w-4 text-muted-foreground ml-2" />
                <input
                  ref={inputRef}
                  value={q}
                  onChange={(e) => setQ(e.target.value)}
                  placeholder="جستجو فیلم، سریال، موزیک..."
                  className="bg-transparent flex-1 px-2 text-sm outline-none placeholder:text-muted-foreground"
                />
                <button type="button" onClick={() => setSearchOpen(false)} aria-label="بستن جستجو">
                  <X className="h-4 w-4 text-muted-foreground hover:text-white" />
                </button>
              </div>
              {suggestions.length > 0 && q.length === 0 && (
                <div className="absolute top-full mt-2 right-0 w-[280px] glass-strong rounded-xl p-2 shadow-xl">
                  <div className="text-[10px] text-muted-foreground px-2 py-1">جستجوهای اخیر</div>
                  {suggestions.map((s, i) => (
                    <button
                      key={i}
                      type="button"
                      onClick={() => { search(s); setSearchOpen(false); }}
                      className="w-full text-right px-2 py-1.5 rounded-lg hover:bg-white/5 text-sm"
                    >
                      <Search className="h-3 w-3 inline ml-2 text-muted-foreground" />
                      {s}
                    </button>
                  ))}
                </div>
              )}
            </form>
          ) : (
            <button
              onClick={() => setSearchOpen(true)}
              className="flex h-10 w-10 items-center justify-center rounded-full hover:bg-white/10 transition"
              aria-label="جستجو"
            >
              <Search className="h-5 w-5" />
            </button>
          )}
        </div>

        {/* Notifications */}
        <button
          onClick={() => navigate("profile")}
          className="hidden md:flex h-10 w-10 items-center justify-center rounded-full hover:bg-white/10 transition relative"
          aria-label="اعلان‌ها"
        >
          <Bell className="h-5 w-5" />
          <span className="absolute top-2 right-2 h-2 w-2 rounded-full bg-secondary" />
        </button>

        {/* Premium / Profile */}
        {user ? (
          <button
            onClick={() => navigate("profile")}
            className="flex items-center gap-2 rounded-full glass hover:bg-white/10 px-2 py-1 transition"
          >
            <div className="flex h-8 w-8 items-center justify-center rounded-full bg-gradient-brand text-xs font-bold text-white">
              {user.name.charAt(0)}
            </div>
            <span className="hidden md:inline text-sm font-medium max-w-[100px] truncate">{user.name}</span>
          </button>
        ) : (
          <button
            onClick={() => navigate("subscription")}
            className="hidden sm:inline-flex items-center gap-1.5 rounded-full bg-gradient-brand hover:opacity-90 px-4 py-2 text-sm font-bold text-white shadow-glow transition"
          >
            <Crown className="h-4 w-4" /> اشتراک VIP
          </button>
        )}

        <button
          onClick={() => navigate("profile")}
          className="md:hidden flex h-10 w-10 items-center justify-center rounded-full hover:bg-white/10"
          aria-label="پروفایل"
        >
          <User className="h-5 w-5" />
        </button>
      </div>
    </header>
  );
}

function PlayIcon() {
  return (
    <svg viewBox="0 0 24 24" className="h-5 w-5" fill="white">
      <path d="M8 5v14l11-7z" />
    </svg>
  );
}
