"use client";

import Link from "next/link";
import { usePathname } from "next/navigation";
import { useEffect } from "react";
import {
  TrendingUp,
  LayoutDashboard,
  ArrowLeftRight,
  Target,
  CreditCard,
  Landmark,
  Handshake,
  PieChart,
  Zap,
  BarChart2,
  CalendarRange,
  RefreshCw,
  Bot,
  Settings,
  ChevronLeft,
  Wallet,
  X,
  FileBarChart2,
  Users,
} from "lucide-react";
import { cn } from "@/lib/utils/cn";
import { useUIStore } from "@/store/ui.store";
import { Button } from "@/components/ui/button";

const NAV_ITEMS = [
  { label: "Dashboard", href: "/dashboard", icon: LayoutDashboard },
  { label: "Accounts", href: "/bank-accounts", icon: Wallet },
  { label: "Transactions", href: "/transactions", icon: ArrowLeftRight },
  { label: "Budgets", href: "/budgets", icon: Target },
  { label: "Credit Cards", href: "/credit-cards", icon: CreditCard },
  { label: "Loans", href: "/loans", icon: Landmark },
  { label: "Chit Funds", href: "/chit-funds", icon: Users },
  { label: "IOUs", href: "/ious", icon: Handshake },
  { label: "Net Worth", href: "/net-worth", icon: PieChart },
  { label: "Debt Simulator", href: "/debt-simulator", icon: Zap },
  { label: "Recurring", href: "/recurring", icon: RefreshCw },
  { label: "Analytics", href: "/analytics", icon: BarChart2 },
  { label: "Reports", href: "/reports", icon: FileBarChart2 },
  { label: "Projections", href: "/projections", icon: CalendarRange },
  { label: "AI Adviser", href: "/advisor", icon: Bot },
];

export function Sidebar() {
  const pathname = usePathname();
  const { sidebarOpen, toggleSidebar, setSidebarOpen } = useUIStore();

  // Start closed on mobile so the sidebar doesn't block content on first load
  useEffect(() => {
    if (window.innerWidth < 768) setSidebarOpen(false);
  }, [setSidebarOpen]);

  function handleNavClick() {
    // Close drawer on mobile after navigation
    if (typeof window !== "undefined" && window.innerWidth < 768 && sidebarOpen) {
      toggleSidebar();
    }
  }

  return (
    <>
      {/* Mobile backdrop */}
      {sidebarOpen && (
        <div
          className="fixed inset-0 bg-black/60 z-40 md:hidden"
          onClick={toggleSidebar}
        />
      )}

      <aside
        className={cn(
          "flex flex-col bg-slate-900 border-r border-slate-700/50 transition-all duration-200",
          // Mobile: fixed overlay; Desktop: static in flex row
          "fixed inset-y-0 left-0 z-50 md:static md:z-auto",
          // Mobile: slide based on open state; Desktop: always visible
          sidebarOpen ? "translate-x-0" : "-translate-x-full md:translate-x-0",
          // Width: always w-64 on mobile, collapse on desktop
          "w-64",
          sidebarOpen ? "md:w-56" : "md:w-16"
        )}
      >
        <div className="flex items-center justify-between px-4 py-5 border-b border-slate-700/50">
          <div className="flex items-center gap-2">
            <div className="rounded-lg bg-emerald-500 p-1.5 shrink-0">
              <TrendingUp className="h-4 w-4 text-white" />
            </div>
            {(sidebarOpen) && (
              <span className="font-bold text-white text-lg tracking-tight">FinPulse</span>
            )}
          </div>
          {/* Close button — mobile only */}
          {sidebarOpen && (
            <button
              onClick={toggleSidebar}
              className="md:hidden text-slate-500 hover:text-white transition-colors"
            >
              <X className="h-5 w-5" />
            </button>
          )}
        </div>

        <nav className="flex-1 px-2 py-4 space-y-0.5 overflow-y-auto">
          {NAV_ITEMS.map(({ label, href, icon: Icon }) => {
            const active = pathname === href || pathname.startsWith(href + "/");
            return (
              <Link
                key={href}
                href={href}
                onClick={handleNavClick}
                className={cn(
                  "flex items-center gap-3 px-3 py-2.5 rounded-lg text-sm font-medium transition-colors",
                  active
                    ? "bg-emerald-500/15 text-emerald-400"
                    : "text-slate-400 hover:bg-slate-800 hover:text-slate-200"
                )}
              >
                <Icon className="h-4 w-4 shrink-0" />
                {sidebarOpen && <span>{label}</span>}
              </Link>
            );
          })}
        </nav>

        <div className="px-2 py-4 border-t border-slate-700/50 space-y-0.5">
          <Link
            href="/settings"
            onClick={handleNavClick}
            className={cn(
              "flex items-center gap-3 px-3 py-2.5 rounded-lg text-sm font-medium transition-colors",
              pathname.startsWith("/settings")
                ? "bg-emerald-500/15 text-emerald-400"
                : "text-slate-400 hover:bg-slate-800 hover:text-slate-200"
            )}
          >
            <Settings className="h-4 w-4 shrink-0" />
            {sidebarOpen && <span>Settings</span>}
          </Link>
          {/* Collapse toggle — desktop only */}
          <Button
            variant="ghost"
            size="sm"
            onClick={toggleSidebar}
            className="hidden md:flex w-full justify-start text-slate-500 hover:text-slate-300 hover:bg-slate-800"
          >
            <ChevronLeft
              className={cn(
                "h-4 w-4 shrink-0 transition-transform",
                !sidebarOpen && "rotate-180"
              )}
            />
            {sidebarOpen && <span className="ml-3">Collapse</span>}
          </Button>
        </div>
      </aside>
    </>
  );
}
