"use client";

import Link from "next/link";
import { usePathname, useRouter } from "next/navigation";
import { Building2, FileText, Inbox, LayoutDashboard, LogOut, MapPin, Repeat } from "lucide-react";
import type { AdminRole, AdminUser } from "@/lib/adminApi";
import Logo from "../Logo";

const items: { href: string; label: string; icon: typeof Inbox; roles: AdminRole[] }[] = [
  { href: "/admin", label: "Inicio", icon: LayoutDashboard, roles: ["admin", "editor", "sales"] },
  { href: "/admin/leads", label: "Leads", icon: Inbox, roles: ["admin", "sales"] },
  { href: "/admin/properties", label: "Propiedades", icon: Building2, roles: ["admin", "editor"] },
  { href: "/admin/articles", label: "Artículos", icon: FileText, roles: ["admin", "editor"] },
  { href: "/admin/locations", label: "Zonas", icon: MapPin, roles: ["admin", "editor"] },
  { href: "/admin/exchange-rate", label: "Tasa COP/USD", icon: Repeat, roles: ["admin", "editor"] },
];

const roleLabel: Record<AdminRole, string> = { admin: "Administrador", editor: "Editor", sales: "Comercial" };

export default function AdminNav({ user }: { user: AdminUser }) {
  const pathname = usePathname();
  const router = useRouter();

  const logout = async () => {
    await fetch("/api/v1/auth/logout", { method: "POST" });
    router.replace("/admin/login");
    router.refresh();
  };

  return (
    <aside className="flex flex-col bg-ink text-cream md:min-h-screen md:w-60">
      <div className="px-6 py-6">
        <Logo className="h-9" />
        <p className="mt-2 text-[0.6rem] tracking-[0.4em] text-gold-light">PANEL</p>
      </div>
      <nav className="flex gap-1 overflow-x-auto px-3 pb-3 md:flex-1 md:flex-col md:overflow-visible">
        {items
          .filter((item) => item.roles.includes(user.role))
          .map(({ href, label, icon: Icon }) => {
            const active = href === "/admin" ? pathname === "/admin" : pathname.startsWith(href);
            return (
              <Link
                key={href}
                href={href}
                className={`flex shrink-0 items-center gap-3 px-3 py-2.5 text-sm transition ${active ? "bg-cream/10 text-gold-light" : "text-cream/70 hover:text-cream"}`}
              >
                <Icon size={16} strokeWidth={1.5} /> {label}
              </Link>
            );
          })}
      </nav>
      <div className="hidden border-t border-cream/10 px-6 py-5 text-sm md:block">
        <p className="truncate">{user.name}</p>
        <p className="text-xs text-cream/70">{roleLabel[user.role]}</p>
        <button type="button" onClick={logout} className="mt-4 flex items-center gap-2 text-xs text-cream/80 hover:text-gold-light">
          <LogOut size={14} strokeWidth={1.5} /> Cerrar sesión
        </button>
      </div>
    </aside>
  );
}
