import { useState } from "react";
import { NavLink } from "react-router-dom";
import {
  ArrowLeft,
  ChevronLeft,
  ChevronRight,
  ClipboardList,
  Landmark,
  Menu,
  ReceiptText,
  Settings,
  UserCircle2,
  Users,
  Wallet,
  X,
} from "lucide-react";
import { Button } from "@/components/ui/button";
import { cn } from "@/lib/utils";
import { GlobalFunctions } from "@/GlobalFunctions";
import { useAuthAccess } from "@/contexts/AuthAccessContext";

const navItems = [
  {
    section: "Fechamento",
    title: "Gerenciar Fechamentos",
    path: "",
    icon: ClipboardList,
    roles: ["admin"] as const,
  },
  {
    section: "Fechamento",
    title: "Banco de Pontos",
    path: "banco-pontos",
    icon: Landmark,
    roles: ["admin"] as const,
  },
  {
    section: "Fechamento",
    title: "Meu Fechamento",
    path: "meu-fechamento",
    icon: ReceiptText,
    roles: ["admin", "parceiro"] as const,
  },
  {
    section: "Configurações",
    title: "Parceiros",
    path: "parceiros",
    icon: Wallet,
    roles: ["admin"] as const,
  },
  {
    section: "Configurações",
    title: "Usuários",
    path: "usuarios",
    icon: Users,
    roles: ["admin"] as const,
  },
  {
    section: "Configurações",
    title: "Configurações",
    path: "configuracoes",
    icon: Settings,
    roles: ["admin"] as const,
  },
  {
    section: "Configurações",
    title: "Meu Perfil",
    path: "meu-perfil",
    icon: UserCircle2,
    roles: ["admin", "parceiro"] as const,
  },
];

export function AppSidebar() {
  const { papel } = useAuthAccess();
  const [collapsed, setCollapsed] = useState(false);
  const [mobileOpen, setMobileOpen] = useState(false);
  const isAdmin = papel === "admin";
  const role = papel ?? "parceiro";
  const allowedNavItems = navItems.filter((item) => item.roles.includes(role));
  const sections = ["Fechamento", "Configurações"] as const;

  const SidebarContent = () => (
    <>
      <div
        className={cn(
          "border-b border-sidebar-border max-lg:pt-12",
          collapsed
            ? "flex flex-col items-center gap-2 px-2 py-3"
            : "flex items-center gap-2 px-3 py-4 lg:gap-3",
        )}
      >
        {!collapsed ? (
          <>
            <div className="flex min-w-0 flex-1 items-center gap-3">
              <div className="flex h-10 w-10 flex-shrink-0 items-center justify-center rounded-xl bg-primary/10 cyber-glow">
                <ClipboardList className="h-5 w-5 text-primary" />
              </div>
              <div className="min-w-0 animate-fade-in">
                <h1 className="truncate text-lg font-semibold text-sidebar-foreground">HGTX Intelligence Score</h1>
                <p className="text-xs text-muted-foreground">{isAdmin ? "Painel Admin" : "Painel Parceiro"}</p>
              </div>
            </div>
            <Button
              type="button"
              variant="ghost"
              size="icon"
              className="hidden h-8 w-8 flex-shrink-0 text-muted-foreground hover:text-foreground lg:inline-flex"
              title="Recolher menu"
              aria-label="Recolher menu"
              onClick={() => setCollapsed(true)}
            >
              <ChevronLeft className="h-4 w-4" />
            </Button>
          </>
        ) : (
          <>
            <Button
              type="button"
              variant="ghost"
              size="icon"
              className="hidden h-8 w-8 text-muted-foreground hover:text-foreground lg:inline-flex"
              title="Expandir menu"
              aria-label="Expandir menu"
              onClick={() => setCollapsed(false)}
            >
              <ChevronRight className="h-4 w-4" />
            </Button>
            <div className="flex h-10 w-10 items-center justify-center rounded-xl bg-primary/10 cyber-glow">
              <ClipboardList className="h-5 w-5 text-primary" />
            </div>
          </>
        )}
      </div>

      <nav className="flex-1 space-y-3 px-3 py-4">
        {sections.map((section) => {
          const sectionItems = allowedNavItems.filter((item) => item.section === section);
          if (sectionItems.length === 0) {
            return null;
          }

          return (
            <div key={section} className="space-y-1">
              {!collapsed ? (
                <p className="px-3 pb-1 text-xs font-semibold uppercase tracking-wide text-muted-foreground/80">
                  {section}
                </p>
              ) : null}
              {sectionItems.map((item) => (
                <NavLink
                  key={item.path}
                  to={item.path}
                  end={item.path === ""}
                  onClick={() => setMobileOpen(false)}
                  className={({ isActive }) =>
                    cn(
                      "nav-item flex w-full items-center gap-3 rounded-lg px-3 py-2.5 text-sm font-medium transition-all duration-200",
                      isActive
                        ? "bg-sidebar-accent font-medium text-primary"
                        : "text-muted-foreground hover:bg-sidebar-accent hover:text-foreground",
                    )
                  }
                >
                  <item.icon className="h-5 w-5 flex-shrink-0" />
                  {!collapsed && <span className="animate-fade-in">{item.title}</span>}
                </NavLink>
              ))}
            </div>
          );
        })}
      </nav>

      <div className="mt-auto border-t border-sidebar-border p-3">
        <Button
          type="button"
          variant="ghost"
          onClick={() => {
            GlobalFunctions.handleNavigateBack();
            setMobileOpen(false);
          }}
          className={cn(
            "w-full gap-2 text-sidebar-foreground hover:bg-sidebar-accent hover:text-foreground",
            collapsed ? "justify-center px-0" : "justify-start",
          )}
          title="Voltar ao CORE HGTX"
        >
          <ArrowLeft className="h-4 w-4 flex-shrink-0" />
          {!collapsed && <span>Voltar</span>}
        </Button>
      </div>
    </>
  );

  return (
    <>
      <button
        onClick={() => {
          setCollapsed(false);
          setMobileOpen(true);
        }}
        className="fixed left-4 top-4 z-50 rounded-lg border border-border bg-card p-2 shadow-sm lg:hidden"
      >
        <Menu className="h-5 w-5" />
      </button>

      {mobileOpen && (
        <div
          className="fixed inset-0 z-40 bg-background/80 backdrop-blur-sm lg:hidden"
          onClick={() => setMobileOpen(false)}
        />
      )}

      <aside
        className={cn(
          "fixed left-0 top-0 z-50 flex h-full w-64 flex-col border-r border-sidebar-border bg-sidebar transition-transform duration-300 lg:hidden",
          mobileOpen ? "translate-x-0" : "-translate-x-full",
        )}
      >
        <button
          onClick={() => setMobileOpen(false)}
          className="absolute right-4 top-4 rounded-lg p-2 hover:bg-sidebar-accent"
        >
          <X className="h-5 w-5" />
        </button>
        <SidebarContent />
      </aside>

      <aside
        className={cn(
          "sticky top-0 hidden h-screen flex-col border-r border-sidebar-border bg-sidebar transition-all duration-300 lg:flex",
          collapsed ? "w-[72px]" : "w-64",
        )}
      >
        <SidebarContent />
      </aside>
    </>
  );
}
