"use client";
import { usePathname, useRouter } from "next/navigation";
import { motion, AnimatePresence } from "framer-motion";
import {
  Home,
  Search,
  Grid3x3,
  Heart,
  MessageCircle,
  Package,
  BarChart2,
  List,
  Plus,
  DollarSign,
  User,
  Settings,
  X,
  ChevronLeft,
  ChevronRight,
  Store,
  ShoppingBag,
  type LucideProps,
} from "lucide-react";
import { useMarketplaceContext } from "@/contexts/marketplace/MarketplaceContext";
import { useWishlist } from "@/lib/WishlistContext";
import { useMessaging } from "@/lib/MessagingContext";

type LucideIcon = React.ForwardRefExoticComponent<
  Omit<LucideProps, "ref"> & React.RefAttributes<SVGSVGElement>
>;

interface NavItem {
  id: string;
  label: string;
  href: string;
  icon: LucideIcon;
  badge?: number;
  exact?: boolean;
}

interface NavSection {
  title?: string;
  icon?: LucideIcon;
  items: NavItem[];
}

/* ── NavLink — defined OUTSIDE MarketplaceSidebar to prevent remount ────── */
function NavLink({
  item,
  collapsed,
  onNavigate,
}: {
  item: NavItem;
  collapsed: boolean;
  onNavigate: () => void;
}) {
  const pathname = usePathname();
  const router = useRouter();
  const active = item.exact ? pathname === item.href : pathname === item.href;

  return (
    <button
      onClick={() => {
        router.push(item.href);
        onNavigate();
      }}
      title={collapsed ? item.label : undefined}
      style={{
        width: "100%",
        display: "flex",
        alignItems: "center",
        gap: 10,
        padding: collapsed ? "10px 0" : "9px 12px",
        justifyContent: collapsed ? "center" : "flex-start",
        borderRadius: 10,
        border: "none",
        cursor: "pointer",
        background: active ? "rgba(252,0,0,0.1)" : "transparent",
        color: active ? "var(--accent)" : "var(--text-muted)",
        position: "relative",
        transition: "background 0.15s, color 0.15s",
        textAlign: "left",
      }}
      onMouseEnter={(e) => {
        if (!active)
          (e.currentTarget as HTMLElement).style.background =
            "rgba(255,255,255,0.05)";
      }}
      onMouseLeave={(e) => {
        if (!active)
          (e.currentTarget as HTMLElement).style.background = "transparent";
      }}
    >
      {/* Red accent bar for active */}
      {active && (
        <motion.div
          layoutId="sidebar-active-bar"
          style={{
            position: "absolute",
            left: 0,
            top: "25%",
            transform: "translateY(-50%)",
            width: 3,
            height: 20,
            borderRadius: "0 3px 3px 0",
            background: "var(--accent)",
          }}
        />
      )}

      <item.icon
        size={17}
        color={active ? "var(--accent)" : "var(--text-muted)"}
        style={{ flexShrink: 0 }}
      />

      {!collapsed && (
        <span
          style={{
            flex: 1,
            fontSize: 13,
            fontWeight: active ? 700 : 500,
            color: active ? "var(--accent)" : "var(--text-muted)",
            whiteSpace: "nowrap",
            overflow: "hidden",
            textOverflow: "ellipsis",
          }}
        >
          {item.label}
        </span>
      )}

      {!collapsed && item.badge !== undefined && item.badge > 0 && (
        <span
          style={{
            minWidth: 18,
            height: 18,
            padding: "0 5px",
            borderRadius: 9,
            background: active ? "var(--accent)" : "rgba(255,255,255,0.15)",
            color: active ? "#fff" : "var(--text-muted)",
            fontSize: 9,
            fontWeight: 800,
            display: "flex",
            alignItems: "center",
            justifyContent: "center",
            flexShrink: 0,
          }}
        >
          {item.badge > 9 ? "9+" : item.badge}
        </span>
      )}

      {/* Badge dot when collapsed */}
      {collapsed && item.badge !== undefined && item.badge > 0 && (
        <span
          style={{
            position: "absolute",
            top: 6,
            right: 8,
            width: 7,
            height: 7,
            borderRadius: "50%",
            background: "var(--accent)",
          }}
        />
      )}
    </button>
  );
}

/* ── SidebarContent — also defined outside ──────────────────────────────── */
function SidebarContent({
  sections,
  collapsed,
  toggleSidebar,
  closeMobileSidebar,
  isMobile,
}: {
  sections: NavSection[];
  collapsed: boolean;
  toggleSidebar: () => void;
  closeMobileSidebar: () => void;
  isMobile: boolean;
}) {
  return (
    <div style={{ display: "flex", flexDirection: "column", height: "100%" }}>
      {/* Sidebar header */}
      {/* <div
        style={{
          height: 64,
          display: "flex",
          alignItems: "center",
          justifyContent: collapsed && !isMobile ? "center" : "space-between",
          padding: collapsed && !isMobile ? "0" : "0 16px",
          borderBottom: "1px solid var(--border)",
          flexShrink: 0,
        }}
      >
        {isMobile && (
          <div style={{ display: "flex", alignItems: "center", gap: 8 }}>
            <div
              style={{
                width: 28,
                height: 28,
                borderRadius: 8,
                background:
                  "linear-gradient(135deg, var(--accent) 0%, #ff4040 100%)",
                display: "flex",
                alignItems: "center",
                justifyContent: "center",
              }}
            >
              <Store size={14} color="#fff" />
            </div>
            <span
              style={{
                fontSize: 13,
                fontWeight: 800,
                color: "var(--text-primary)",
              }}
            >
              Marketplace
            </span>
          </div>
        )}
        <button
          onClick={isMobile ? closeMobileSidebar : toggleSidebar}
          aria-label={
            isMobile ? "Close menu" : collapsed ? "Expand" : "Collapse"
          }
          style={{
            width: 28,
            height: 28,
            borderRadius: 7,
            display: "flex",
            alignItems: "center",
            justifyContent: "center",
            color: "var(--text-muted)",
            background: "transparent",
            border: "none",
            cursor: "pointer",
            transition: "background 0.15s",
          }}
          onMouseEnter={(e) => {
            (e.currentTarget as HTMLElement).style.background =
              "rgba(255,255,255,0.08)";
          }}
          onMouseLeave={(e) => {
            (e.currentTarget as HTMLElement).style.background = "transparent";
          }}
        >
          {isMobile ? (
            <X size={16} />
          ) : collapsed ? (
            <ChevronRight size={14} />
          ) : (
            <ChevronLeft size={14} />
          )}
        </button>
      </div> */}

      {/* Nav sections */}
      <nav
        style={{
          flex: 1,
          overflowY: "auto",
          overflowX: "hidden",
          padding: "12px 8px",
          display: "flex",
          flexDirection: "column",
          gap: 20,
        }}
      >
        {sections.map((section, i) => (
          <div key={i}>
            {section.title && !collapsed && (
              <p
                style={{
                  fontSize: 9,
                  fontWeight: 800,
                  letterSpacing: "0.1em",
                  textTransform: "uppercase",
                  color: "var(--text-muted)",
                  opacity: 0.5,
                  padding: "0 12px",
                  marginBottom: 6,
                }}
              >
                {section.title}
              </p>
            )}
            {section.title && collapsed && (
              <div
                style={{
                  borderTop: "1px solid var(--border)",
                  marginBottom: 8,
                  opacity: 0.4,
                }}
              />
            )}
            <div style={{ display: "flex", flexDirection: "column", gap: 1 }}>
              {section.items.map((item) => (
                <NavLink
                  key={item.id}
                  item={item}
                  collapsed={collapsed}
                  onNavigate={closeMobileSidebar}
                />
              ))}
            </div>
          </div>
        ))}
      </nav>

      {/* Footer version */}
      {!collapsed && (
        <div
          style={{
            padding: "12px 16px",
            borderTop: "1px solid var(--border)",
            flexShrink: 0,
          }}
        >
          <p style={{ fontSize: 10, color: "var(--text-muted)", opacity: 0.4 }}>
            Marketplace v2.0
          </p>
        </div>
      )}
    </div>
  );
}

/* ── Main export ─────────────────────────────────────────────────────────── */
export function MarketplaceSidebar() {
  const { sidebarOpen, toggleSidebar, closeMobileSidebar, mobileSidebarOpen } =
    useMarketplaceContext();
  const { count: wishlistCount } = useWishlist();
  const { totalUnread } = useMessaging();

  const sections: NavSection[] = [
    {
      items: [
        {
          id: "home",
          label: "Home",
          href: "/marketplace",
          icon: Home,
          exact: true,
        },
        // {
        //   id: "search",
        //   label: "Browse",
        //   href: "/marketplace/search",
        //   icon: Search,
        // },
        {
          id: "categories",
          label: "Categories",
          href: "/marketplace/categories",
          icon: Grid3x3,
        },
        {
          id: "wishlist",
          label: "Wishlist",
          href: "/marketplace/wishlist",
          icon: Heart,
          badge: wishlistCount,
        },
        {
          id: "messages",
          label: "Messages",
          href: "/marketplace/messages",
          icon: MessageCircle,
          badge: totalUnread,
        },
        {
          id: "orders",
          label: "My Orders",
          href: "/marketplace/orders",
          icon: Package,
        },
      ],
    },
    {
      title: "Sell",
      items: [
        {
          id: "dashboard",
          label: "Dashboard",
          href: "/marketplace/seller",
          icon: BarChart2,
        },

        {
          id: "sell-orders",
          label: "Orders",
          href: "/marketplace/seller/orders",
          icon: ShoppingBag,
        },
        {
          id: "earnings",
          label: "Earnings",
          href: "/marketplace/seller/earnings",
          icon: DollarSign,
        },
        {
          id: "create",
          label: "New Listing",
          href: "/marketplace/create",
          icon: Plus,
        },
      ],
    },
    {
      title: "Account",
      items: [
        {
          id: "profile",
          label: "Profile",
          href: "/marketplace/profile",
          icon: User,
        },
        {
          id: "settings",
          label: "Settings",
          href: "/marketplace/settings",
          icon: Settings,
        },
      ],
    },
  ];

  const collapsed = !sidebarOpen;

  return (
    <>
      {/* ── Desktop sidebar ────────────────────────────────────────────────── */}
      <motion.aside
        animate={{ width: collapsed ? 60 : 240 }}
        transition={{ type: "spring", stiffness: 320, damping: 32 }}
        style={{
          flexShrink: 0,
          height: "100%",
          overflow: "hidden",
          background: "var(--card)",
          borderRight: "1px solid var(--border)",
        }}
        className="hidden md:block"
      >
        <SidebarContent
          sections={sections}
          collapsed={collapsed}
          toggleSidebar={toggleSidebar}
          closeMobileSidebar={closeMobileSidebar}
          isMobile={false}
        />
      </motion.aside>

      {/* ── Mobile drawer ──────────────────────────────────────────────────── */}
      <AnimatePresence>
        {mobileSidebarOpen && (
          <>
            {/* Backdrop */}
            <motion.div
              key="backdrop"
              initial={{ opacity: 0 }}
              animate={{ opacity: 1 }}
              exit={{ opacity: 0 }}
              transition={{ duration: 0.22 }}
              onClick={closeMobileSidebar}
              style={{
                position: "fixed",
                inset: 0,
                zIndex: 40,
                background: "rgba(0,0,0,0.65)",
                backdropFilter: "blur(4px)",
              }}
              className="md:hidden"
            />
            {/* Drawer panel */}
            <motion.aside
              key="drawer"
              initial={{ x: "-100%" }}
              animate={{ x: 0 }}
              exit={{ x: "-100%" }}
              transition={{ type: "spring", stiffness: 320, damping: 32 }}
              style={{
                position: "fixed",
                left: 0,
                top: 0,
                bottom: 0,
                width: 280,
                zIndex: 50,
                background: "var(--card)",
                borderRight: "1px solid var(--border)",
              }}
              className="md:hidden"
            >
              <SidebarContent
                sections={sections}
                collapsed={false}
                toggleSidebar={toggleSidebar}
                closeMobileSidebar={closeMobileSidebar}
                isMobile={true}
              />
            </motion.aside>
          </>
        )}
      </AnimatePresence>
    </>
  );
}
