"use client";

import Link from "next/link";
import { usePathname } from "next/navigation";
import { motion, AnimatePresence } from "framer-motion";
import {
  LayoutDashboard,
  ReceiptText,
  Users,
  PackageSearch,
  Wallet,
  BellRing,
  FileBarChart,
  LineChart,
  FileText,
  Settings,
  ChevronsLeft,
  X,
} from "lucide-react";
import { cn } from "@/lib/cn";
import { useAuth } from "@/lib/auth/auth-provider";
import { useAdminOrders } from "@/lib/data/admin-orders-provider";
import { useAdminNotifications } from "@/lib/data/admin-notifications-provider";

const NAV_GROUPS = [
  {
    label: "Overview",
    items: [{ href: "/", label: "Dashboard", icon: LayoutDashboard }],
  },
  {
    label: "Operations",
    items: [
      { href: "/orders", label: "Orders", icon: ReceiptText, badgeKey: "orders" as const },
      { href: "/users", label: "Users", icon: Users },
      { href: "/packages", label: "Packages", icon: PackageSearch },
      { href: "/payments", label: "Payments", icon: Wallet },
    ],
  },
  {
    label: "Insights",
    items: [
      { href: "/analytics", label: "Analytics", icon: LineChart },
      { href: "/reports", label: "Reports", icon: FileBarChart },
    ],
  },
  {
    label: "System",
    items: [
      { href: "/notifications", label: "Notifications", icon: BellRing, badgeKey: "notifications" as const },
      { href: "/cms", label: "Website Content", icon: FileText },
      { href: "/settings", label: "Settings", icon: Settings },
    ],
  },
];

export function Sidebar({
  collapsed,
  onToggleCollapsed,
  mobileOpen,
  onCloseMobile,
}: {
  collapsed: boolean;
  onToggleCollapsed: () => void;
  mobileOpen: boolean;
  onCloseMobile: () => void;
}) {
  const pathname = usePathname();
  const { user, profile } = useAuth();
  const { orders } = useAdminOrders();
  const pendingOrders = orders.filter((o) => o.status === "pending").length;
  const { unreadCount: unreadNotifications } = useAdminNotifications();
  const displayName = profile?.full_name || user?.email?.split("@")[0] || "Admin";
  const initials = displayName.slice(0, 2).toUpperCase();

  const badgeFor = (key?: "orders" | "notifications") => {
    if (key === "orders") return pendingOrders;
    if (key === "notifications") return unreadNotifications;
    return 0;
  };

  const content = (
    <div className="flex h-full flex-col">
      <div className={cn("flex items-center gap-2.5 px-5 pt-6 pb-5", collapsed && "justify-center px-0")}>
        <div className="flex h-9 w-9 shrink-0 items-center justify-center rounded-xl bg-gradient-to-br from-gold-bright to-gold-dim font-display text-base font-bold text-ink shadow-glow-gold">
          S
        </div>
        {!collapsed && (
          <div className="min-w-0">
            <p className="truncate font-display text-[15px] font-semibold leading-tight">
              SharedNet
            </p>
            <p className="text-[11px] text-muted">Admin Panel</p>
          </div>
        )}
      </div>

      <nav className="no-scrollbar flex-1 overflow-y-auto px-3">
        {NAV_GROUPS.map((group) => (
          <div key={group.label} className="mb-4">
            {!collapsed && (
              <p className="px-3 pb-1.5 text-[10.5px] font-semibold uppercase tracking-wider text-muted/70">
                {group.label}
              </p>
            )}
            <div className="flex flex-col gap-0.5">
              {group.items.map((item) => {
                const active = pathname === item.href;
                const badge = badgeFor("badgeKey" in item ? item.badgeKey : undefined);
                return (
                  <Link
                    key={item.href}
                    href={item.href}
                    onClick={onCloseMobile}
                    title={collapsed ? item.label : undefined}
                    className={cn(
                      "group relative flex items-center gap-3 rounded-xl px-3 py-2.5 text-sm font-medium transition-colors",
                      collapsed && "justify-center px-0",
                      active
                        ? "bg-gold/12 text-gold-dim dark:text-gold-bright nav-active-rail"
                        : "text-muted hover:bg-black/[0.03] hover:text-ink dark:hover:bg-white/[0.04] dark:hover:text-paper"
                    )}
                  >
                    <item.icon size={18} strokeWidth={2} className="shrink-0" />
                    {!collapsed && <span className="flex-1 truncate">{item.label}</span>}
                    {!collapsed && badge > 0 && (
                      <span className="flex h-5 min-w-5 items-center justify-center rounded-full bg-danger px-1 text-[10.5px] font-bold text-white">
                        {badge}
                      </span>
                    )}
                    {collapsed && badge > 0 && (
                      <span className="absolute right-1.5 top-1.5 h-2 w-2 rounded-full bg-danger" />
                    )}
                  </Link>
                );
              })}
            </div>
          </div>
        ))}
      </nav>

      <div className="border-t border-black/[0.06] p-3 dark:border-white/[0.06]">
        <div className={cn("flex items-center gap-2.5 rounded-xl px-2 py-2", collapsed && "justify-center px-0")}>
          <div className="flex h-9 w-9 shrink-0 items-center justify-center rounded-full bg-gradient-to-br from-gold-bright to-gold-dim font-display text-xs font-bold text-ink">
            {initials}
          </div>
          {!collapsed && (
            <div className="min-w-0 flex-1">
              <p className="truncate text-[13px] font-semibold">{displayName}</p>
              <p className="truncate text-[11px] text-muted">Admin</p>
            </div>
          )}
        </div>
        <button
          onClick={onToggleCollapsed}
          className={cn(
            "mt-1 hidden w-full items-center gap-2 rounded-xl px-3 py-2 text-xs font-medium text-muted transition-colors hover:bg-black/[0.03] hover:text-ink dark:hover:bg-white/[0.04] dark:hover:text-paper lg:flex",
            collapsed && "justify-center px-0"
          )}
        >
          <ChevronsLeft size={16} className={cn("transition-transform", collapsed && "rotate-180")} />
          {!collapsed && "Collapse"}
        </button>
      </div>
    </div>
  );

  return (
    <>
      {/* Desktop sidebar */}
      <aside
        className={cn(
          "sticky top-0 hidden h-dvh shrink-0 border-r border-black/[0.06] bg-paper-elevated transition-[width] duration-200 dark:border-white/[0.06] dark:bg-ink-elevated lg:block",
          collapsed ? "w-[76px]" : "w-64"
        )}
      >
        {content}
      </aside>

      {/* Mobile drawer */}
      <AnimatePresence>
        {mobileOpen && (
          <>
            <motion.div
              initial={{ opacity: 0 }}
              animate={{ opacity: 1 }}
              exit={{ opacity: 0 }}
              onClick={onCloseMobile}
              className="fixed inset-0 z-40 bg-ink/50 backdrop-blur-sm lg:hidden"
            />
            <motion.aside
              initial={{ x: -280 }}
              animate={{ x: 0 }}
              exit={{ x: -280 }}
              transition={{ type: "spring", stiffness: 350, damping: 34 }}
              className="fixed inset-y-0 left-0 z-50 w-72 bg-paper-elevated shadow-2xl dark:bg-ink-elevated lg:hidden"
            >
              <div className="flex justify-end px-3 pt-3">
                <button
                  onClick={onCloseMobile}
                  className="flex h-9 w-9 items-center justify-center rounded-full hover:bg-black/5 dark:hover:bg-white/5"
                >
                  <X size={18} />
                </button>
              </div>
              {content}
            </motion.aside>
          </>
        )}
      </AnimatePresence>
    </>
  );
}
