"use client";

import { usePathname } from "next/navigation";
import Link from "next/link";
import { useAppSelector } from "@/lib/store";
import type { User as AuthUser } from "@/modules/auth/types";
import {
  Sidebar,
  SidebarContent,
  SidebarHeader,
  SidebarFooter,
  SidebarMenu,
  SidebarMenuItem,
  SidebarMenuButton,
  SidebarGroup,
  SidebarGroupContent,
  SidebarGroupLabel,
} from "@/components/ui/sidebar";
import {
  LayoutDashboard,
  Stamp,
  FileCheck2,
  Users,
  ClipboardList,
  ShieldCheck,
  BarChart3,
  Handshake,
  Megaphone,
  Building,
  UserIcon,
  User2Icon,
  Briefcase,
  FileText,
  User,
  CreditCard,
  LogOut,
} from "lucide-react";
import { useLogout } from "@/modules/auth/hooks/auth.hooks";

export function AppSidebar({
  initialUser = null,
}: {
  initialUser?: AuthUser | null;
}) {
  const { user, isLoading } = useAppSelector((state) => state.auth);
  const pathname = usePathname();

  const effectiveUser = user ?? initialUser;
  const userRole = effectiveUser?.role || "";

  const { mutate: logout } = useLogout();
  const handleLogout = () => logout();

  const getNavItems = () => {
    if (!userRole) return [];
    if (userRole === "SUPERADMIN") {
      return [
        {
          label: "Super Admin",
          items: [
            {
              title: "Dashboard",
              href: "/superadmin/dashboard",
              icon: LayoutDashboard,
            },
            { title: "All Firms", href: "/superadmin/firms", icon: Building },
            { title: "All Users", href: "/superadmin/users", icon: Users },
            {
              title: "Compliance",
              href: "/superadmin/compliance",
              icon: ShieldCheck,
            },
            { title: "Finance", href: "/superadmin/finance", icon: BarChart3 },
            {
              title: "Marketplace",
              href: "/superadmin/marketplace",
              icon: Handshake,
            },
            {
              title: "Marketing",
              href: "/superadmin/marketing",
              icon: Megaphone,
            },
          ],
        },
      ];
    }
    if (userRole === "ADMIN") {
      return [
        {
          label: "Admin Management",
          items: [
            {
              title: "Dashboard",
              href: "/admin/dashboard",
              icon: LayoutDashboard,
            },

            {
              title: "Departments",
              href: "/admin/departments",
              icon: Building,
            },
            { title: "Employees", href: "/admin/employees", icon: Users },
            { title: "Clients", href: "/admin/clients", icon: User2Icon },
            {
              title: "Services",
              href: "/admin/services",
              icon: ClipboardList,
            },
            {
              title: "Tasks",
              href: "/admin/tasks",
              icon: FileCheck2,
            },
            {
              title: "Transactions",
              href: "/admin/transactions",
              icon: CreditCard,
            },
            {
              title: "Profile",
              href: "/profile",
              icon: UserIcon,
            },
          ],
        },
      ];
    }
    if (userRole === "MANAGER") {
      return [
        {
          label: "Manager Portal",
          items: [
            {
              title: "Dashboard",
              href: "/manager/dashboard",
              icon: LayoutDashboard,
            },
            // { title: "My Team", href: "/manager/team", icon: Users },
            { title: "Tasks", href: "/manager/tasks", icon: FileCheck2 },
            {
              title: "Profile",
              href: "/profile",
              icon: UserIcon,
            },
            // {
            //   title: "Department Queue",
            //   href: "/manager/queue",
            //   icon: ClipboardList,
            // },
            // { title: "Clients", href: "/manager/clients", icon: Building2 },
            // { title: "Reports", href: "/manager/reports", icon: BarChart3 },
          ],
        },
      ];
    }
    if (userRole === "EMPLOYEE") {
      return [
        {
          label: "Staff Portal",
          items: [
            {
              title: "Dashboard",
              href: "/employee/dashboard",
              icon: LayoutDashboard,
            },
            { title: "My Tasks", href: "/employee/tasks", icon: FileCheck2 },
            // {
            //   title: "Department Queue",
            //   href: "/employee/queue",
            //   icon: ClipboardList,
            // },
            // { title: "Leads", href: "/employee/leads", icon: Handshake },
            {
              title: "Profile",
              href: "/profile",
              icon: UserIcon,
            },
          ],
        },
      ];
    }
    return [
      {
        label: "Client Management",
        items: [
          {
            title: "Dashboard",
            href: "/client/dashboard",
            icon: LayoutDashboard,
          },
          {
            title: "Services",
            href: "/client/services",
            icon: Briefcase,
          },
          {
            title: "My Applications",
            href: "/client/tasks",
            icon: FileText,
          },
          {
            title: "Profile",
            href: "/profile",
            icon: UserIcon,
          },
          // {
          //   title: "Documents",
          //   href: "/client/documents",
          //   icon: FolderOpenDot,
          // },
          // {
          //   title: "Invoices & Payments",
          //   href: "/client/invoices",
          //   icon: Receipt,
          // },
          // {
          //   title: "My Businesses",
          //   href: "/client/businesses",
          //   icon: Building2,
          // },
          // { title: "Notifications", href: "/client/notifications", icon: Bell },
          // {
          //   title: "AI Assistant",
          //   href: "/client/ai-assistant",
          //   icon: Sparkles,
          // },
        ],
      },
    ];
  };

  const sidebarStyle = {
    background:
      "linear-gradient(180deg, hsl(var(--sidebar-background)) 0%, hsl(215 51% 12%) 100%)",
  };
  if (isLoading && !userRole) {
    return (
      <Sidebar
        className="border-r border-sidebar-border"
        style={sidebarStyle}
        collapsible="icon"
      >
        <SidebarHeader className="flex h-20 items-center justify-center border-b border-sidebar-border/60 px-5">
          <div className="flex items-center gap-3 font-display font-semibold text-sidebar-foreground">
            <span className="flex h-10 w-10 items-center justify-center rounded-xl bg-[hsl(var(--sidebar-primary))] text-[hsl(var(--sidebar-primary-foreground))] shadow-sm">
              <Stamp className="h-5 w-5" />
            </span>
            <span className="group-data-[collapsible=icon]:hidden tracking-tight text-lg">
              TaxFend
            </span>
          </div>
        </SidebarHeader>

        <SidebarContent className="py-5" />

        <SidebarFooter className="border-t border-sidebar-border/60 p-4">
          <div className="flex items-center gap-3 rounded-2xl bg-white/5 px-3 py-2.5 group-data-[collapsible=icon]:justify-center">
            <span className="flex h-10 w-10 flex-shrink-0 items-center justify-center rounded-full bg-[hsl(var(--sidebar-primary))] text-[hsl(var(--sidebar-primary-foreground))] text-sm font-bold">
              {""}
            </span>
            <div className="flex flex-col text-left group-data-[collapsible=icon]:hidden min-w-0">
              <span className="text-sm font-medium text-white truncate">
                User
              </span>
              <span className="text-xs text-sidebar-foreground/50"></span>
            </div>
          </div>
        </SidebarFooter>
      </Sidebar>
    );
  }

  const navGroups = getNavItems();
  const initials = (effectiveUser?.name || "U")
    .split(" ")
    .map((n) => n[0])
    .slice(0, 2)
    .join("")
    .toUpperCase();
  const roleLabelMap: Record<string, string> = {
    SUPERADMIN: "Super Admin",
    ADMIN: "Admin",
    MANAGER: "Manager",
    EMPLOYEE: "Staff",
    CLIENT: "Client",
  };
  const roleLabel = roleLabelMap[userRole ?? ""] ?? "";

  return (
    <Sidebar
      className="border-r border-sidebar-border"
      style={{
        background:
          "linear-gradient(180deg, hsl(var(--sidebar-background)) 0%, hsl(215 51% 12%) 100%)",
      }}
      collapsible="icon"
    >
      <SidebarHeader className="flex h-20 items-center justify-center border-b border-sidebar-border/60 px-5">
        <div className="flex items-center gap-3 font-display font-semibold text-sidebar-foreground">
          <span className="flex h-10 w-10 items-center justify-center rounded-xl bg-[hsl(var(--sidebar-primary))] text-[hsl(var(--sidebar-primary-foreground))] shadow-sm">
            <Stamp className="h-5 w-5" />
          </span>
          <span className="group-data-[collapsible=icon]:hidden tracking-tight text-lg">
            TaxFend
          </span>
        </div>
      </SidebarHeader>

      <SidebarContent className="py-5 scrollbar-hide">
        {navGroups.map((group) => (
          <SidebarGroup key={group.label}>
            <SidebarGroupLabel className="text-sidebar-foreground/40 uppercase tracking-[0.15em] text-[11px] group-data-[collapsible=icon]:hidden px-5 mb-3 font-bold">
              {group.label}
            </SidebarGroupLabel>
            <SidebarGroupContent>
              <SidebarMenu className="gap-2 px-3">
                {group.items.map((item) => {
                  const isActive = pathname === item.href;
                  return (
                    <SidebarMenuItem key={item.title}>
                      <SidebarMenuButton
                        asChild
                        size="lg"
                        isActive={isActive}
                        tooltip={item.title}
                        className={`relative justify-start gap-3 rounded-2xl px-4 !py-3 text-sm font-medium [&>svg]:size-5 data-[active=true]:bg-[hsl(var(--sidebar-primary)/0.14)] data-[active=true]:text-white data-[active=true]:before:absolute data-[active=true]:before:left-0 data-[active=true]:before:top-2 data-[active=true]:before:bottom-2 data-[active=true]:before:w-[3px] data-[active=true]:before:rounded-full data-[active=true]:before:bg-[hsl(var(--sidebar-primary))] text-sidebar-foreground/65 hover:text-white hover:bg-white/5`}
                      >
                        <Link
                          href={item.href}
                          className="flex items-center gap-3 w-full"
                        >
                          <item.icon
                            className={
                              isActive
                                ? "text-[hsl(var(--sidebar-primary))] shrink-0"
                                : "text-sidebar-foreground/60 shrink-0"
                            }
                          />
                          <span className="group-data-[collapsible=icon]:hidden">
                            {item.title}
                          </span>
                        </Link>
                      </SidebarMenuButton>
                    </SidebarMenuItem>
                  );
                })}
              </SidebarMenu>
            </SidebarGroupContent>
          </SidebarGroup>
        ))}
      </SidebarContent>

      <SidebarFooter className="border-t border-sidebar-border/60 p-4">
        <div className="flex items-center gap-3 rounded-2xl bg-white/5 px-3 py-2.5 group-data-[collapsible=icon]:justify-center">
          <span className="flex h-10 w-10 flex-shrink-0 items-center justify-center rounded-full bg-[hsl(var(--sidebar-primary))] text-[hsl(var(--sidebar-primary-foreground))] text-sm font-bold">
            {initials}
          </span>

          <div className="flex flex-col text-left group-data-[collapsible=icon]:hidden min-w-0">
            <span className="text-sm font-medium text-white truncate">
              {effectiveUser?.name || "User"}
            </span>

            <span className="text-xs text-sidebar-foreground/50">
              {roleLabel}
            </span>
          </div>

          {/* Logout */}
          <button
            type="button"
            onClick={handleLogout}
            className="ml-auto flex-shrink-0 cursor-pointer text-destructive hover:text-destructive/80"
          >
            <LogOut className="h-5 w-5" />
          </button>
        </div>
      </SidebarFooter>
    </Sidebar>
  );
}
