import { clsx } from "clsx";
import { Gamepad2 } from "lucide-react";
import { useLocation, useNavigate } from "react-router-dom";

import { NAV_ITEMS } from "@/constants/navigation";
import { confirmDiscardUnsavedChanges } from "@/hooks/useUnsavedChanges";

export function Sidebar() {
  const location = useLocation();
  const navigate = useNavigate();

  async function handleNavigate(path: string) {
    if (path === location.pathname) return;
    const canLeave = await confirmDiscardUnsavedChanges();
    if (canLeave) navigate(path);
  }

  return (
    <aside className="flex h-full w-60 shrink-0 flex-col border-r border-border bg-surface">
      <div className="flex items-center gap-2.5 px-5 py-5">
        <div className="flex h-8 w-8 items-center justify-center rounded-lg bg-accent text-accent-fg">
          <Gamepad2 size={18} />
        </div>
        <div>
          <p className="text-sm font-semibold text-fg leading-tight">8BitDo Control Center</p>
          <p className="text-[11px] text-fg-subtle leading-tight">Ultimate Controller</p>
        </div>
      </div>

      <nav className="flex-1 space-y-0.5 overflow-y-auto px-3 pb-4">
        {NAV_ITEMS.map((item) => {
          const active = location.pathname === item.path;
          const Icon = item.icon;
          return (
            <button
              key={item.path}
              onClick={() => handleNavigate(item.path)}
              className={clsx(
                "flex w-full cursor-pointer items-center gap-3 rounded-lg px-3 py-2 text-left text-sm transition-colors duration-150",
                active
                  ? "bg-accent/15 text-accent-strong font-medium"
                  : "text-fg-muted hover:bg-surface-2 hover:text-fg",
              )}
            >
              <Icon size={16} className="shrink-0" />
              {item.label}
            </button>
          );
        })}
      </nav>
    </aside>
  );
}
