"use client";

import Link from "next/link";
import { usePathname } from "next/navigation";
import { useEffect, useState } from "react";
import {
  LayoutDashboard,
  Users,
  CalendarCheck,
  CreditCard,
  Settings,
  Brain,
  ChevronLeft,
  Activity,
} from "lucide-react";
import { UserButton, useUser } from "@clerk/nextjs";
import { usePendingRecommendationsCount } from "@/hooks/use-api";
import { cn } from "@/lib/utils";

interface NavItem {
  icon: React.ElementType;
  label: string;
  href: string;
  badge?: number;
}

export function Sidebar() {
  const pathname = usePathname();
  const { user } = useUser();
  const { data: pendingCount = 0 } = usePendingRecommendationsCount();
  const [mounted, setMounted] = useState(false);
  const [isCollapsed, setIsCollapsed] = useState(false);

  useEffect(() => {
    setMounted(true);
    const saved = localStorage.getItem("sidebar-collapsed");
    if (saved) setIsCollapsed(JSON.parse(saved));
  }, []);

  const handleToggle = () => {
    const newState = !isCollapsed;
    setIsCollapsed(newState);
    localStorage.setItem("sidebar-collapsed", JSON.stringify(newState));
  };

  const navItems: NavItem[] = [
    { icon: LayoutDashboard, label: "Dashboard", href: "/" },
    { icon: Users, label: "Users", href: "/users" },
    {
      icon: Brain,
      label: "AI Recommendations",
      href: "/recommendations",
      badge: pendingCount > 0 ? pendingCount : undefined,
    },
    { icon: CalendarCheck, label: "Attendance", href: "/attendance" },
    { icon: CreditCard, label: "Payments", href: "/payments" },
    { icon: Settings, label: "Settings", href: "/settings" },
  ];

  return (
    <aside
      className={cn(
        "fixed left-0 top-0 z-40 h-screen transition-all duration-300 ease-in-out",
        isCollapsed ? "w-[72px]" : "w-[260px]",
        "bg-gradient-to-b from-[var(--sidebar-background)] to-[#0f172a]",
      )}
    >
      <div className="flex h-full flex-col border-r border-white/5">
        {/* Logo */}
        <div
          className={cn(
            "flex h-16 items-center border-b border-white/5 px-4",
            isCollapsed ? "justify-center" : "justify-between",
          )}
        >
          {!isCollapsed && (
            <Link href="/" className="flex items-center gap-2">
              <div className="flex h-9 w-9 items-center justify-center rounded-lg bg-gradient-to-br from-blue-500 to-indigo-600 shadow-lg shadow-blue-500/25">
                <Activity className="h-5 w-5 text-white" />
              </div>
              <span className="text-lg font-bold text-white">FitAI</span>
            </Link>
          )}
          {isCollapsed && (
            <div className="flex h-9 w-9 items-center justify-center rounded-lg bg-gradient-to-br from-blue-500 to-indigo-600 shadow-lg shadow-blue-500/25">
              <Activity className="h-5 w-5 text-white" />
            </div>
          )}
        </div>

        {/* Toggle Button */}
        <button
          onClick={handleToggle}
          className={cn(
            "absolute -right-3 top-20 z-50 flex h-6 w-6 items-center justify-center rounded-full border border-white/10 bg-slate-800 text-white/60 shadow-lg transition-all hover:bg-slate-700 hover:text-white",
            isCollapsed ? "left-[60px]" : "left-[244px]",
          )}
        >
          <ChevronLeft
            className={cn(
              "h-3.5 w-3.5 transition-transform",
              isCollapsed && "rotate-180",
            )}
          />
        </button>

        {/* Navigation */}
        <nav className="flex-1 space-y-1 overflow-y-auto p-3">
          {navItems.map((item) => {
            const Icon = item.icon;
            const isActive =
              pathname === item.href ||
              (item.href !== "/" && pathname.startsWith(item.href));

            return (
              <Link
                key={item.href}
                href={item.href}
                className={cn(
                  "group flex items-center gap-3 rounded-lg px-3 py-2.5 text-sm font-medium transition-all duration-200",
                  isActive
                    ? "bg-gradient-to-r from-blue-600 to-blue-500 text-white shadow-lg shadow-blue-500/25"
                    : "text-slate-400 hover:bg-white/5 hover:text-white",
                  isCollapsed && "justify-center px-2",
                )}
              >
                <Icon
                  className={cn(
                    "h-5 w-5 flex-shrink-0 transition-colors",
                    isActive
                      ? "text-white"
                      : "text-slate-500 group-hover:text-white",
                  )}
                />
                {!isCollapsed && (
                  <>
                    <span className="flex-1">{item.label}</span>
                    {item.badge !== undefined && (
                      <span className="flex h-5 min-w-[20px] items-center justify-center rounded-full bg-red-500 px-1.5 text-xs font-bold text-white">
                        {item.badge > 99 ? "99+" : item.badge}
                      </span>
                    )}
                  </>
                )}
                {isCollapsed && item.badge !== undefined && (
                  <span className="absolute -right-1 -top-1 flex h-4 min-w-[16px] items-center justify-center rounded-full bg-red-500 px-1 text-[10px] font-bold text-white">
                    {item.badge > 9 ? "9+" : item.badge}
                  </span>
                )}
              </Link>
            );
          })}
        </nav>

        {/* User Section */}
        <div
          className={cn(
            "border-t border-white/5 p-3",
            isCollapsed && "flex justify-center",
          )}
        >
          <div
            className={cn(
              "flex items-center gap-3 rounded-lg bg-white/5 p-2 transition-colors hover:bg-white/10",
              isCollapsed && "justify-center p-2",
            )}
          >
            <div className={cn("flex-shrink-0", isCollapsed ? "" : "ml-1")}>
              {mounted && <UserButton afterSignOutUrl="/" />}
            </div>
            {!isCollapsed && (
              <div className="min-w-0 flex-1">
                <p className="truncate text-sm font-medium text-white">
                  {user?.fullName || "Admin"}
                </p>
                <p className="truncate text-xs text-slate-400">
                  {user?.primaryEmailAddress?.emailAddress}
                </p>
              </div>
            )}
          </div>
        </div>
      </div>
    </aside>
  );
}
