"use client";

import { useLogout } from "@/hooks/useAuthMutation";
import { useState } from "react";
import Link from "next/link";
import { usePathname } from "next/navigation";
import { cn } from "@/lib/utils";
import {
  BarChart3,
  Users,
  Settings,
  FileText,
  LayoutDashboard,
  MessageSquare,
  CreditCard,
  LogOut,
  Menu,
  X,
  ChevronDown,
} from "lucide-react";
import { Button } from "@/components/ui/button";

const menuItems = [
  {
    title: "Dashboard",
    icon: LayoutDashboard,
    href: "/admin",
  },
  {
    title: "Analytics",
    icon: BarChart3,
    href: "/admin/analytics",
  },
  {
    title: "Member",
    icon: Users,
    href: "/admin/member",
    subItems: [
      { title: "All Members", href: "/admin/member" },
      { title: "Add New", href: "/admin/member/new" },
    ],
  },

  {
    title: "Users",
    icon: Users,
    href: "/admin/users",
    badge: "12",
  },
  {
    title: "Messages",
    icon: MessageSquare,
    href: "/admin/messages",
    badge: "5",
  },
  {
    title: "Reports",
    icon: FileText,
    href: "/admin/reports",
  },
  {
    title: "Billing",
    icon: CreditCard,
    href: "/admin/billing",
  },
  {
    title: "Settings",
    icon: Settings,
    href: "/admin/settings",
  },
];

export function AdminSidebar() {
  const pathname = usePathname();
  const [isOpen, setIsOpen] = useState(false);
  // Track which submenu is open
  const [openMenus, setOpenMenus] = useState<string[]>([]);
  const { mutate: logout, isPending: isLoggingOut } = useLogout();

  const isActive = (href: string) => {
    return (
      pathname === href || (href !== "/admin" && pathname.startsWith(href))
    );
  };

  const toggleSubmenu = (title: string) => {
    setOpenMenus((prev) =>
      prev.includes(title) ? prev.filter((i) => i !== title) : [...prev, title],
    );
  };

  return (
    <>
      {/* Mobile Menu Button */}
      <div className="fixed top-0 left-0 right-0 h-16 bg-sidebar border-b border-sidebar-border flex items-center px-4 md:hidden z-50">
        <Button
          variant="ghost"
          size="icon"
          onClick={() => setIsOpen(!isOpen)}
          className="text-sidebar-foreground"
        >
          {isOpen ? <X className="w-5 h-5" /> : <Menu className="w-5 h-5" />}
        </Button>
        <h1 className="ml-4 font-bold text-sidebar-foreground">Admin</h1>
      </div>

      {/* Sidebar Overlay (Mobile) */}
      {isOpen && (
        <div
          className="fixed inset-0 bg-black/50 md:hidden z-40"
          onClick={() => setIsOpen(false)}
        />
      )}

      {/* Sidebar */}
      <aside
        className={cn(
          "fixed left-0 top-0 bottom-0 w-64 bg-sidebar border-r border-sidebar-border transition-transform duration-300 z-40",
          "pt-20 md:pt-6 md:translate-x-0",
          isOpen ? "translate-x-0" : "-translate-x-full md:translate-x-0",
        )}
      >
        <div className="px-4 py-6 space-y-1">
          <div className="px-4 pb-4 mb-6 hidden md:block">
            <div className="font-bold text-lg text-sidebar-foreground">
              Admin Panel
            </div>
            <p className="text-xs text-sidebar-foreground/60">Dashboard</p>
          </div>

          <nav className="space-y-1">
            {menuItems.map((item) => {
              const Icon = item.icon;
              const active = isActive(item.href);
              const hasSubmenu = item.subItems && item.subItems.length > 0;
              const isExpanded = openMenus.includes(item.title);

              return (
                <div key={item.title} className="space-y-1">
                  {hasSubmenu ? (
                    // Dropdown Trigger
                    <button
                      onClick={() => toggleSubmenu(item.title)}
                      className={cn(
                        "w-full flex items-center justify-between px-4 py-3 rounded-lg transition-colors group",
                        active && !isExpanded
                          ? "bg-sidebar-primary text-sidebar-primary-foreground"
                          : "text-sidebar-foreground hover:bg-sidebar-accent hover:text-sidebar-accent-foreground",
                      )}
                    >
                      <div className="flex items-center gap-3">
                        <Icon className="w-5 h-5" />
                        <span className="text-sm font-medium">
                          {item.title}
                        </span>
                      </div>
                      <ChevronDown
                        className={cn(
                          "w-4 h-4 transition-transform duration-200",
                          isExpanded && "rotate-180",
                        )}
                      />
                    </button>
                  ) : (
                    // Regular Link
                    <Link href={item.href}>
                      <button
                        onClick={() => setIsOpen(false)}
                        className={cn(
                          "w-full flex items-center justify-between px-4 py-3 rounded-lg transition-colors",
                          active
                            ? "bg-sidebar-primary text-sidebar-primary-foreground"
                            : "text-sidebar-foreground hover:bg-sidebar-accent hover:text-sidebar-accent-foreground",
                        )}
                      >
                        <div className="flex items-center gap-3">
                          <Icon className="w-5 h-5" />
                          <span className="text-sm font-medium">
                            {item.title}
                          </span>
                        </div>
                        {item.badge && (
                          <span
                            className={cn(
                              "inline-flex items-center justify-center px-2 py-1 rounded-full text-xs font-semibold",
                              active
                                ? "bg-sidebar-primary-foreground/20"
                                : "bg-sidebar-accent",
                            )}
                          >
                            {item.badge}
                          </span>
                        )}
                      </button>
                    </Link>
                  )}

                  {/* Submenu Content */}
                  {hasSubmenu && isExpanded && (
                    <div className="ml-9 space-y-1">
                      {item.subItems?.map((sub) => (
                        <Link key={sub.href} href={sub.href}>
                          <button
                            onClick={() => setIsOpen(false)}
                            className={cn(
                              "w-full text-left px-4 py-2 rounded-md text-sm transition-colors",
                              pathname === sub.href
                                ? "text-sidebar-primary font-semibold"
                                : "text-sidebar-foreground/70 hover:text-sidebar-foreground hover:bg-sidebar-accent",
                            )}
                          >
                            {sub.title}
                          </button>
                        </Link>
                      ))}
                    </div>
                  )}
                </div>
              );
            })}
          </nav>

          <div className="my-6 border-t border-sidebar-border" />

          <div className="space-y-2">
            <button
              type="button"
              disabled={isLoggingOut}
              onClick={() => logout()}
              className="w-full flex items-center gap-3 px-4 py-3 rounded-lg text-sidebar-foreground hover:bg-sidebar-accent hover:text-sidebar-accent-foreground transition-colors text-sm font-medium disabled:opacity-50"
            >
              <LogOut className="w-5 h-5" />
              <span>{isLoggingOut ? "Logging out…" : "Logout"}</span>
            </button>
          </div>
        </div>
      </aside>

      <div className="hidden md:block w-64" />
    </>
  );
}
