"use client";

import Link from "next/link";
import { useState, useEffect, useRef } from "react";
import { Search, Menu, X, User, ShoppingBag, FileText, Trophy, Newspaper, LayoutDashboard, LogOut, ChevronDown, ShieldCheck } from "lucide-react";
import { motion, AnimatePresence } from "framer-motion";
import { usePathname } from "next/navigation";
import { useAuth } from "@/lib/auth";

import { APP_CONFIG } from "@/lib/branding";

const navLinks = [
  { label: "Topup", href: "/", icon: ShoppingBag },
  { label: "Cek Transaksi", href: "/invoice", icon: FileText },
  { label: "Leaderboard", href: "/leaderboard", icon: Trophy },
  { label: "Artikel", href: "/article", icon: Newspaper },
];

export default function Navbar() {
  const [scrolled, setScrolled] = useState(false);
  const [mobileOpen, setMobileOpen] = useState(false);
  const [searchOpen, setSearchOpen] = useState(false);
  const [searchQuery, setSearchQuery] = useState("");
  const [userMenuOpen, setUserMenuOpen] = useState(false);
  const pathname = usePathname();
  const { user, loading, logout } = useAuth();
  const menuRef = useRef<HTMLDivElement>(null);

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

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

  const handleLogout = async () => {
    setUserMenuOpen(false);
    await logout();
    window.location.href = "/";
  };

  return (
    <nav
      className={`fixed top-0 left-0 right-0 z-50 h-[60px] flex items-center transition-all duration-300 ${
        scrolled
          ? "glass-strong shadow-lg"
          : "bg-dark/80 backdrop-blur-md"
      }`}
    >
      <div className="max-w-7xl mx-auto px-4 flex w-full items-center justify-between gap-4">
        {/* Logo */}
        <Link href="/" className="flex items-center gap-2 shrink-0 group">
          <div className="w-8 h-8 rounded-xl overflow-hidden ring-1 ring-white/10 group-hover:ring-primary/50 transition-all">
            <img src="/images/logo.webp" alt={APP_CONFIG.name} className="w-full h-full object-cover" />
          </div>
          <div>
            <span className="font-heading text-lg font-bold text-primary">{APP_CONFIG.brand}</span>
            <span className="font-heading text-lg font-bold text-secondary"> {APP_CONFIG.subBrand}</span>
          </div>
        </Link>

        {/* Desktop Nav */}
        <div className="hidden lg:flex items-center gap-0.5">
          {navLinks.map((link) => {
            const Icon = link.icon;
            const isActive = pathname === link.href;
            return (
              <Link
                key={link.href}
                href={link.href}
                className={`flex items-center gap-1.5 px-4 py-2 text-sm font-medium rounded-lg transition-all duration-200 ${
                  isActive
                    ? "text-primary"
                    : "text-muted hover:text-white hover:bg-white/5"
                }`}
              >
                <Icon size={15} className={isActive ? "text-primary" : ""} />
                {link.label}
              </Link>
            );
          })}
        </div>

        {/* Search + Auth */}
        <div className="flex items-center gap-2">
          {/* Search Toggle */}
          <button
            onClick={() => setSearchOpen(!searchOpen)}
            className="p-2 rounded-xl hover:bg-white/10 transition-colors text-muted hover:text-white"
          >
            <Search size={18} />
          </button>

          {/* Auth: User avatar or Login button */}
          {!loading && user ? (
            <div ref={menuRef} className="relative">
              <button
                onClick={() => setUserMenuOpen(!userMenuOpen)}
                className="hidden md:flex items-center gap-2 px-2 py-1.5 rounded-xl hover:bg-white/5 transition-all"
              >
                <div className="w-8 h-8 rounded-full overflow-hidden ring-2 ring-primary/30 flex items-center justify-center bg-dark-surface">
                  {/* eslint-disable-next-line @next/next/no-img-element */}
                  <img src={user.avatar || "/images/logo.webp"} alt={user.username} className="w-full h-full object-cover" referrerPolicy="no-referrer" />
                </div>
                <span className="text-xs font-medium text-white max-w-[80px] truncate">{user.username}</span>
                <ChevronDown size={12} className={`text-muted transition-transform ${userMenuOpen ? "rotate-180" : ""}`} />
              </button>

              {/* Dropdown menu */}
              <AnimatePresence>
                {userMenuOpen && (
                  <motion.div
                    initial={{ opacity: 0, y: -5, scale: 0.95 }}
                    animate={{ opacity: 1, y: 0, scale: 1 }}
                    exit={{ opacity: 0, y: -5, scale: 0.95 }}
                    transition={{ duration: 0.15 }}
                    className="absolute right-0 top-full mt-2 w-56 rounded-xl glass-strong border border-dark-border shadow-2xl overflow-hidden"
                  >
                    {/* User info */}
                    <div className="px-4 py-3 border-b border-dark-border">
                      <p className="text-sm font-semibold text-white truncate">{user.username}</p>
                      <p className="text-[10px] text-muted truncate">{user.email}</p>
                      <div className="mt-2 flex items-center gap-2">
                        <span className="text-[9px] text-primary font-bold bg-primary/10 px-1.5 py-0.5 rounded">XCredits: {user.xcredits?.toLocaleString("id-ID") || "0"}</span>
                      </div>
                    </div>

                    {/* Menu items */}
                    <div className="py-1">
                      <Link
                        href="/dashboard"
                        onClick={() => setUserMenuOpen(false)}
                        className="flex items-center gap-3 px-4 py-2.5 text-xs font-medium text-muted hover:text-white hover:bg-white/5 transition-colors"
                      >
                        <LayoutDashboard size={14} /> Dashboard
                      </Link>
                      <Link
                        href="/dashboard/settings"
                        onClick={() => setUserMenuOpen(false)}
                        className="flex items-center gap-3 px-4 py-2.5 text-xs font-medium text-muted hover:text-white hover:bg-white/5 transition-colors"
                      >
                        <User size={14} /> Pengaturan
                      </Link>
                      {user.role === "admin" && (
                        <Link
                          href="/admin"
                          onClick={() => setUserMenuOpen(false)}
                          className="flex items-center gap-3 px-4 py-2.5 text-xs font-medium text-red-400 hover:bg-red-500/10 transition-colors"
                        >
                          <ShieldCheck size={14} /> Admin Panel
                        </Link>
                      )}
                    </div>

                    {/* Logout */}
                    <div className="border-t border-dark-border py-1">
                      <button
                        onClick={handleLogout}
                        className="flex items-center gap-3 w-full px-4 py-2.5 text-xs font-medium text-red-400 hover:bg-red-500/10 transition-colors"
                      >
                        <LogOut size={14} /> Keluar
                      </button>
                    </div>
                  </motion.div>
                )}
              </AnimatePresence>
            </div>
          ) : !loading ? (
            <Link
              href="/login"
              className="hidden md:flex items-center gap-2 btn-primary text-xs py-2 px-4"
            >
              <User size={14} />
              Masuk
            </Link>
          ) : null}

          {/* Mobile Menu Toggle */}
          <button
            onClick={() => setMobileOpen(!mobileOpen)}
            className="lg:hidden p-2 rounded-xl hover:bg-white/10 text-muted hover:text-white"
          >
            {mobileOpen ? <X size={20} /> : <Menu size={20} />}
          </button>
        </div>
      </div>

      {/* Search Bar Dropdown */}
      <AnimatePresence>
        {searchOpen && (
          <motion.div
            initial={{ opacity: 0, y: -10 }}
            animate={{ opacity: 1, y: 0 }}
            exit={{ opacity: 0, y: -10 }}
            className="absolute top-full left-0 right-0 px-4 py-3 glass-strong"
          >
            <div className="max-w-2xl mx-auto relative">
              <Search size={16} className="absolute left-4 top-1/2 -translate-y-1/2 text-muted" />
              <input
                type="text"
                value={searchQuery}
                onChange={(e) => setSearchQuery(e.target.value)}
                placeholder="Cari Game atau Voucher..."
                className="input-field pl-11"
                autoFocus
              />
            </div>
          </motion.div>
        )}
      </AnimatePresence>

      {/* Mobile Menu */}
      <AnimatePresence>
        {mobileOpen && (
          <motion.div
            initial={{ opacity: 0, height: 0 }}
            animate={{ opacity: 1, height: "auto" }}
            exit={{ opacity: 0, height: 0 }}
            className="lg:hidden glass-strong border-t border-dark-border"
          >
            <div className="px-4 py-4 space-y-1">
              {navLinks.map((link) => {
                const Icon = link.icon;
                const isActive = pathname === link.href;
                return (
                  <Link
                    key={link.href}
                    href={link.href}
                    onClick={() => setMobileOpen(false)}
                    className={`flex items-center gap-3 px-4 py-3 text-sm font-medium rounded-lg transition-colors ${
                      isActive
                        ? "text-primary bg-primary/10"
                        : "text-muted hover:text-white hover:bg-white/5"
                    }`}
                  >
                    <Icon size={16} />
                    {link.label}
                  </Link>
                );
              })}

              {user ? (
                <>
                  <Link
                    href="/dashboard"
                    onClick={() => setMobileOpen(false)}
                    className="flex items-center gap-3 px-4 py-3 text-sm font-medium rounded-lg text-muted hover:text-white hover:bg-white/5"
                  >
                    <LayoutDashboard size={16} /> Dashboard
                  </Link>
                  <button
                    onClick={() => { setMobileOpen(false); handleLogout(); }}
                    className="flex items-center gap-3 w-full px-4 py-3 text-sm font-medium rounded-lg text-red-400 hover:bg-red-500/10"
                  >
                    <LogOut size={16} /> Keluar
                  </button>
                </>
              ) : (
                <Link
                  href="/login"
                  onClick={() => setMobileOpen(false)}
                  className="block text-center btn-primary text-sm mt-3"
                >
                  Masuk
                </Link>
              )}
            </div>
          </motion.div>
        )}
      </AnimatePresence>
    </nav>
  );
}
