"use client";

import { useState } from "react";
import Link from "next/link";
import { usePathname } from "next/navigation";
import { useSession } from "next-auth/react";
import { motion, useReducedMotion } from "motion/react";
import { cn } from "@/lib/utils";
import { springSoft } from "@/lib/motion";
import { BrandLockup, BrandLogo } from "@/components/brand/brand-logo";
import {
  Users,
  LayoutDashboard,
  Settings,
  PanelLeftClose,
  PanelLeft,
  Building2,
  TrendingUp,
  Briefcase,
  type LucideIcon,
} from "lucide-react";

const workspaceNav = [
  { name: "Dashboard", href: "/dashboard", icon: LayoutDashboard },
  { name: "Users", href: "/dashboard/users", icon: Users },
  { name: "Analytics", href: "/dashboard/analytics", icon: TrendingUp },
];

const orgNav = [
  { name: "Departments", href: "/dashboard/departments", icon: Building2 },
  { name: "Designations", href: "/dashboard/designations", icon: Briefcase },
];

const accountNav = [
  { name: "Settings", href: "/dashboard/settings", icon: Settings },
];

function canAccessHR(role: string, department: string) {
  if (role === "SUPER_ADMIN" || role === "UPPER_MANAGEMENT") return true;
  if (role === "MANAGER" && department === "HR") return true;
  return false;
}

function isActivePath(pathname: string, href: string) {
  if (href === "/dashboard") {
    return (
      pathname === "/dashboard" ||
      pathname === "/dashboard/admin" ||
      pathname === "/dashboard/manager" ||
      pathname === "/dashboard/lead" ||
      pathname === "/dashboard/member" ||
      pathname === "/dashboard/management"
    );
  }
  return pathname === href || pathname.startsWith(href + "/");
}

export function Sidebar() {
  const [collapsed, setCollapsed] = useState(false);
  const pathname = usePathname();
  const { data: session } = useSession();
  const reduceMotion = useReducedMotion();

  const showHR = session?.user
    ? canAccessHR(session.user.role, session.user.department)
    : false;

  const getInitials = (name: string) =>
    name
      .split(" ")
      .map((w) => w.charAt(0))
      .join("")
      .toUpperCase()
      .slice(0, 2);

  const NavLink = ({
    name,
    href,
    icon: Icon,
  }: {
    name: string;
    href: string;
    icon: LucideIcon;
  }) => {
    const active = isActivePath(pathname, href);
    return (
      <Link
        href={href}
        prefetch={false}
        title={collapsed ? name : undefined}
        className={cn(
          "relative flex items-center gap-3 rounded-xl px-2.5 py-2 text-sm font-medium transition-colors z-0",
          active
            ? "text-sidebar-accent-foreground"
            : "text-muted-foreground hover:bg-sidebar-muted hover:text-sidebar-foreground",
          collapsed && "justify-center px-0",
        )}
      >
        {active &&
          (reduceMotion ? (
            <span className="absolute inset-0 rounded-xl bg-sidebar-accent -z-10" />
          ) : (
            <motion.span
              layoutId="sidebar-active"
              className="absolute inset-0 rounded-xl bg-sidebar-accent -z-10"
              transition={springSoft}
            />
          ))}
        <Icon className="h-4 w-4 shrink-0 relative z-10" strokeWidth={1.6} />
        {!collapsed && <span className="relative z-10">{name}</span>}
      </Link>
    );
  };

  const Section = ({
    label,
    children,
  }: {
    label: string;
    children: React.ReactNode;
  }) => (
    <div className="space-y-0.5">
      {!collapsed && (
        <p className="px-2.5 pt-4 pb-1.5 text-[10px] font-semibold uppercase tracking-[0.16em] text-muted-foreground/80">
          {label}
        </p>
      )}
      {collapsed && <div className="pt-3" />}
      {children}
    </div>
  );

  return (
    <aside
      className={cn(
        "flex h-full min-h-0 shrink-0 flex-col self-stretch bg-sidebar border-r border-sidebar-border transition-[width] duration-300 ease-in-out",
        collapsed ? "w-[72px]" : "w-[248px]",
      )}
    >
      <div
        className={cn(
          "border-b border-sidebar-border",
          collapsed
            ? "flex h-[76px] flex-col items-center justify-center gap-1 px-1.5 py-2 overflow-hidden"
            : "grid h-[76px] grid-cols-[minmax(0,1fr)_auto] items-center gap-1.5 px-3",
        )}
      >
        {!collapsed ? (
          <>
            <BrandLockup height={38} className="min-w-0 w-full" />
            <motion.button
              type="button"
              onClick={() => setCollapsed(true)}
              whileTap={reduceMotion ? undefined : { scale: 0.92 }}
              className="p-1.5 rounded-lg text-muted-foreground hover:bg-sidebar-muted hover:text-foreground transition-colors"
              aria-label="Collapse sidebar"
            >
              <PanelLeftClose className="h-4 w-4" strokeWidth={1.6} />
            </motion.button>
          </>
        ) : (
          <>
            <BrandLogo markOnly height={20} className="max-w-full shrink-0" />
            <motion.button
              type="button"
              onClick={() => setCollapsed(false)}
              whileTap={reduceMotion ? undefined : { scale: 0.92 }}
              className="p-1.5 rounded-lg text-muted-foreground hover:bg-sidebar-muted hover:text-foreground transition-colors"
              aria-label="Expand sidebar"
            >
              <PanelLeft className="h-4 w-4" strokeWidth={1.6} />
            </motion.button>
          </>
        )}
      </div>

      <nav className="min-h-0 flex-1 overflow-y-auto px-2.5 pb-3">
        <Section label="Main">
          {workspaceNav.map((item) => (
            <NavLink key={item.name} {...item} />
          ))}
        </Section>

        {showHR && (
          <Section label="Organisation">
            {orgNav.map((item) => (
              <NavLink key={item.name} {...item} />
            ))}
          </Section>
        )}

        <Section label="Account">
          {accountNav.map((item) => (
            <NavLink key={item.name} {...item} />
          ))}
        </Section>
      </nav>

      <div className="shrink-0 border-t border-sidebar-border p-2.5">
        <div
          className={cn(
            "flex items-center gap-2.5 rounded-xl px-2 py-2",
            collapsed && "justify-center px-0",
          )}
        >
          <div className="h-8 w-8 rounded-full bg-avatar text-avatar-foreground flex items-center justify-center text-[11px] font-semibold shrink-0">
            {session?.user?.name ? getInitials(session.user.name) : "U"}
          </div>
          {!collapsed && (
            <div className="min-w-0 flex-1">
              <p className="text-sm font-medium truncate text-sidebar-foreground">
                {session?.user?.name || "Loading..."}
              </p>
              <p className="text-xs text-muted-foreground truncate">
                {session?.user?.position || "—"}
              </p>
            </div>
          )}
        </div>
      </div>
    </aside>
  );
}
