"use client";

import Link from "next/link";
import { useCallback, useEffect, useRef, useState } from "react";
import { usePathname } from "next/navigation";
import {
  Home,
  Search,
  Heart,
  Clapperboard,
  Bell,
  MessageCircle,
  Bookmark,
  Plus,
  Moon,
  Sun,
  LogOut,
  Wallet,
  Store,
  ChevronUp,
  Bookmark as BookmarkIcon,
  ShieldCheck,
  Trophy,
  User,
  Users,
  Flag, Megaphone, CalendarDays,
  HeartHandshake, Newspaper, Music, ChevronDown, PlusSquare, Palette, Crown, Briefcase, Tag } from "lucide-react";
import { Avatar } from "./Avatar";
import { ThemeSwitcher } from "./ThemeSwitcher";
import { useAuth } from "@/lib/auth-context";
import { useModules } from "@/lib/modules";
import { useSite } from "@/lib/site-context";
import { useCreatePost } from "@/lib/create-post-context";
import { useTheme } from "@/lib/theme-context";
import { useBadges } from "@/lib/badge-context";
import { useClickOutside } from "@/lib/use-click-outside";
import clsx from "clsx";

const navItems = [
  { href: "/", label: "Home", icon: Home },
  { href: "/communities?tab=group", label: "Groups", icon: Users, module: "communities" },
  { href: "/communities?tab=page", label: "Pages", icon: Flag, module: "communities" },
  { href: "/events", label: "Events", icon: CalendarDays , module: "events" },
  { href: "/activity", label: "Activity", icon: Bell, badgeKey: "activity" as const },
  { href: "/messages", label: "Messages", icon: MessageCircle, badgeKey: "messages" as const },
  { href: "/saved", label: "Saved", icon: Bookmark },
  // Shown only once "More" is opened, so the nav doesn't push the profile
  // tile off the bottom of the screen.
  { href: "/jobs", label: "Jobs", icon: Briefcase, extra: true, module: "jobs" },
  { href: "/offers", label: "Offers", icon: Tag, extra: true, module: "offers" },
  { href: "/leaderboard", label: "Leaderboard", icon: Trophy, extra: true , module: "leaderboard" },
  { href: "/wallet", label: "Wallet", icon: Wallet, extra: true , module: "wallet" },
  { href: "/ads", label: "Adverts", icon: Megaphone, extra: true , module: "ads" },
  { href: "/premium", label: "Go Pro", icon: Crown, extra: true },
];

export function Sidebar() {
  const pathname = usePathname();
  const { user, logout } = useAuth();
  const onReels = pathname === "/reels" || pathname.startsWith("/reels/");
  // Messages is a dense three-pane view, so the nav shrinks to icons there.
  // Reels is a black, full-height player, and a wide white rail beside it
  // fights the thing you came to watch — so it shrinks there too.
  const compact =
    pathname === "/messages" ||
    pathname.startsWith("/messages/") ||
    pathname === "/marketplace" ||
    pathname.startsWith("/marketplace/") ||
    onReels;
  // Nothing on the reels page is a written post, and Create is the widest
  // thing in the rail. On reels the video's own Create button is the one
  // that makes sense, so this one goes.
  const hideCreate = onReels;
  const { open: openComposer } = useCreatePost();
  const { theme, toggle: toggleTheme } = useTheme();
  const { unreadNotifications, unreadMessages } = useBadges();
  const modules = useModules();
  const { siteName } = useSite();
  const [showMore, setShowMore] = useState(false);

  // On a page that lives under "More", open it so the active item is visible.
  const onExtraPage = navItems.some(
    (i) => i.extra && pathname === i.href.split("?")[0]
  );
  // A module switched off in admin disappears from the menu entirely.
  const enabled = navItems.filter(
    (i) => !("module" in i) || modules[(i as { module: string }).module] !== false
  );
  const visible = enabled.filter((i) => !i.extra || showMore || onExtraPage);

  const ROW_HEIGHT = 50;
  const navRef = useRef<HTMLElement | null>(null);
  const [canScrollUp, setCanScrollUp] = useState(false);
  const [canScrollDown, setCanScrollDown] = useState(false);

  /** Keeps the chevrons in step, whether scrolled by click or by wheel. */
  const syncChevrons = useCallback(() => {
    const el = navRef.current;
    if (!el) return;
    setCanScrollUp(el.scrollTop > 1);
    setCanScrollDown(el.scrollTop + el.clientHeight < el.scrollHeight - 1);
  }, []);

  useEffect(syncChevrons, [syncChevrons, enabled.length]);

  const scrollNav = (direction: 1 | -1) => {
    navRef.current?.scrollBy({ top: direction * ROW_HEIGHT * 2, behavior: "smooth" });
  };
  const extraCount = enabled.filter((i) => i.extra).length;
  const [menuOpen, setMenuOpen] = useState(false);
  const [themesOpen, setThemesOpen] = useState(false);
  const menuRef = useClickOutside<HTMLDivElement>(menuOpen, () => setMenuOpen(false));

  if (!user) return null;

  const badgeCounts = { activity: unreadNotifications, messages: unreadMessages };

  return (
    <aside className={clsx(
        "hidden md:flex md:flex-col shrink-0 h-screen sticky top-0 transition-[width] duration-200",
        compact ? "md:w-[72px] px-2 items-center" : "sb-rail"
      )}>
      <div className="sb-card">
        <Link href="/" className="sb-brand">
          <span
            className={clsx(
              "font-black tracking-tight",
              compact ? "text-lg" : "text-2xl"
            )}
          >
            {compact ? siteName.slice(0, 2) : siteName}
          </span>
        </Link>

      {/* The list scrolls inside a fixed window; the rail never changes
          height. Chevrons appear only when there is somewhere to go. */}
      {/* Always here, dimmed when there is nowhere to go. Mounting and
          unmounting them shifted everything below — the Create button
          included — by 24px as the list scrolled. */}
      <button
        onClick={() => scrollNav(-1)}
        disabled={!canScrollUp}
        className="sb-chev"
        aria-label="Scroll up"
      >
        <ChevronUp size={18} />
      </button>

      <nav ref={navRef} onScroll={syncChevrons} className="sb-navwrap flex flex-col">
        {enabled.map(({ href, label, icon: Icon, badgeKey }) => {
          const active = pathname === href || (badgeKey === "messages" && pathname.startsWith("/messages/"));
          const count = badgeKey ? badgeCounts[badgeKey] : 0;
          return (
            <Link
              key={label}
              href={href}
              className={clsx(
                "sb-nav-item relative",
                compact && "justify-center w-11 h-11 p-0",
                active
                  ? "bg-neutral-100 dark:bg-neutral-900 on"
                  : "text-neutral-700 dark:text-neutral-300"
              )}
            >
              <span className="relative">
                <Icon size={27} strokeWidth={active ? 2.2 : 1.8} />
                {count > 0 && (
                  <span className="absolute -top-1 -right-1 min-w-[16px] h-4 px-1 rounded-full bg-rose-500 text-white text-[10px] font-bold flex items-center justify-center">
                    {count > 9 ? "9+" : count}
                  </span>
                )}
              </span>
              {!compact && label}
            </Link>
          );
        })}

      </nav>

      <button
        onClick={() => scrollNav(1)}
        disabled={!canScrollDown}
        className="sb-chev"
        aria-label="Scroll down"
      >
        <ChevronDown size={18} />
      </button>

      {!hideCreate && (
        <button
          onClick={() => openComposer()}
          className={clsx("sb-create", compact && "compact")}
        >
          <PlusSquare size={27} strokeWidth={1.7} /> {!compact && "Create"}
        </button>
      )}
      </div>

      <div className="sb-pinned sb-card flex flex-col gap-1 relative" ref={menuRef}>
        <button
          onClick={(e) => toggleTheme(e)}
          className="flex items-center gap-3 px-3 py-2 rounded-xl text-neutral-500 hover:bg-neutral-50 dark:hover:bg-neutral-900/50 text-[15px] w-fit"
        >
          {theme === "dark" ? <Sun size={19} /> : <Moon size={19} />}
          {!compact && "Modes"}
        </button>
        {/* Account menu — the state existed but nothing ever opened it. */}
        {menuOpen && (
          <div className="sb-menu">
            <Link href={`/${user.username}`} onClick={() => setMenuOpen(false)}>
              <User size={15} /> My profile
            </Link>
            <Link href="/wallet" onClick={() => setMenuOpen(false)}>
              <Wallet size={15} /> Wallet
            </Link>
            <Link href="/ads" onClick={() => setMenuOpen(false)}>
              <Megaphone size={15} /> Adverts
            </Link>
            <Link href="/saved" onClick={() => setMenuOpen(false)}>
              <Bookmark size={15} /> Saved items
            </Link>
            {user.admin && (
              <Link href="/admin" onClick={() => setMenuOpen(false)}>
                <ShieldCheck size={15} /> Admin
              </Link>
            )}
            <button
              onClick={() => {
                setMenuOpen(false);
                setThemesOpen(true);
              }}
            >
              <Palette size={15} /> Switch theme
            </button>

            <span className="sb-menu-sep" />
            <button
              onClick={() => {
                setMenuOpen(false);
                logout();
              }}
              className="danger"
            >
              <LogOut size={15} /> Log out
            </button>
          </div>
        )}

        <button
          onClick={() => setMenuOpen((v) => !v)}
          className="flex items-center gap-3 px-2 py-2 rounded-xl hover:bg-neutral-50 dark:hover:bg-neutral-900/50 transition-colors w-full text-left"
        >
          <Avatar user={user} size={38} />
          {!compact && (
            <>
              <span className="min-w-0 flex-1">
                <span className="block text-sm font-semibold truncate">{user.name}</span>
              </span>
              <ChevronUp
                size={15}
                className={clsx("text-neutral-400 transition-transform", !menuOpen && "rotate-180")}
              />
            </>
          )}
        </button>
      </div>

      {themesOpen && <ThemeSwitcher onClose={() => setThemesOpen(false)} />}

    </aside>
  );
}
