"use client";

import type { LucideIcon } from "lucide-react";
import {
  BarChart3,
  BookOpen,
  Building,
  Building2,
  CalendarRange,
  ChevronDown,
  CircleDollarSign,
  FileBarChart2,
  FileMinus,
  FileText,
  HandCoins,
  Landmark,
  LayoutDashboard,
  LayoutGrid,
  List,
  MessageSquareWarning,
  Receipt,
  RefreshCw,
  Store,
  Tag,
  Users,
  Wallet,
} from "lucide-react";
import Link from "next/link";
import { usePathname } from "next/navigation";
import { useState } from "react";

import { cn } from "@/lib/utils";

type NavItem = {
  href: string;
  label: string;
  shortLabel?: string;
  icon: LucideIcon;
};

type NavGroup = {
  label: string;
  icon: LucideIcon;
  children: NavItem[];
};

const NAV_ITEMS: readonly NavItem[] = [
  { href: "/admin", label: "Tableau de bord", shortLabel: "Dashboard", icon: LayoutDashboard },
  { href: "/admin/residences", label: "Ma résidence", icon: Building2 },
  { href: "/admin/immeubles", label: "Immeubles", icon: Building },
  { href: "/admin/lots", label: "Lots", icon: LayoutGrid },
  { href: "/admin/periodes", label: "Périodes", icon: CalendarRange },
  { href: "/admin/cotisations", label: "Cotisations", icon: CircleDollarSign },
  { href: "/admin/appel_de_fonds", label: "Appels de fonds", shortLabel: "Appels fonds", icon: Wallet },
  { href: "/admin/tresorerie", label: "Trésorerie", icon: Landmark },
  { href: "/admin/exercice_comptable", label: "Exercice comptable", shortLabel: "Exercice", icon: BookOpen },
  {
    href: "/admin/reclamations",
    label: "Réclamations",
    shortLabel: "Réclam.",
    icon: MessageSquareWarning,
  },
  { href: "/admin/documents", label: "Documents", icon: FileText },
  { href: "/admin/utilisateurs", label: "Utilisateurs", icon: Users },
];

const DEPENSE_GROUP: NavGroup = {
  label: "Dépenses",
  icon: HandCoins,
  children: [
    { href: "/admin/depenses", label: "Liste des dépenses", shortLabel: "Dépenses", icon: List },
    { href: "/admin/depenses/recurrentes", label: "Dépenses récurrentes", shortLabel: "Récurrentes", icon: RefreshCw },
    { href: "/admin/depenses/categories", label: "Catégories dépenses", shortLabel: "Catégories", icon: Tag },
    { href: "/admin/depenses/fournisseurs", label: "Fournisseurs", shortLabel: "Fournisseurs", icon: Store },
  ],
};

const RAPPORT_GROUP: NavGroup = {
  label: "Rapports",
  icon: FileBarChart2,
  children: [
    { href: "/admin/rapports", label: "Rapport global", shortLabel: "Global", icon: BarChart3 },
    { href: "/admin/rapports/impayes", label: "Rapport impayées", shortLabel: "Impayées", icon: FileMinus },
    { href: "/admin/rapports/depenses", label: "Rapport dépenses", shortLabel: "Dépenses", icon: Receipt },
  ],
};


function isNavActive(href: string, pathname: string | null): boolean {
  if (!pathname) return false;
  if (href === "/admin") return pathname === "/admin";
  if (href === "/admin/rapports") return pathname === "/admin/rapports";
  if (href === "/admin/depenses") return pathname === "/admin/depenses";
  if (pathname === href) return true;
  return pathname.startsWith(`${href}/`);
}

function isGroupActive(group: NavGroup, pathname: string | null): boolean {
  if (!pathname) return false;
  return group.children.some((child) => isNavActive(child.href, pathname));
}

function DesktopNavLink({
  href,
  label,
  icon: Icon,
  active,
  sub = false,
}: {
  href: string;
  label: string;
  icon: LucideIcon;
  active: boolean;
  sub?: boolean;
}) {
  return (
    <Link
      href={href}
      aria-current={active ? "page" : undefined}
      className={cn(
        "group relative flex items-center gap-3 rounded-lg px-3 py-2 text-sm font-medium transition-all",
        sub && "ml-4",
        active
          ? "bg-primary/10 text-primary shadow-sm"
          : "text-muted-foreground hover:bg-[#0946aa] hover:text-white"
      )}
    >
      <span
        aria-hidden
        className={cn(
          "absolute left-0 top-1/2 h-5 w-[3px] -translate-y-1/2 rounded-r-full transition-all",
          active ? "bg-primary opacity-100" : "bg-transparent opacity-0"
        )}
      />
      <span
        className={cn(
          "flex h-8 w-8 shrink-0 items-center justify-center rounded-md transition-colors",
          sub ? "h-7 w-7" : "",
          active
            ? "bg-primary/10 shadow-sm"
            : "bg-muted/50 group-hover:bg-white/20"
        )}
      >
        <Icon 
          className={cn(
            "h-4 w-4", 
            sub && "h-3.5 w-3.5",
            active 
              ? "text-primary" 
              : "text-muted-foreground group-hover:text-white"
          )} 
          aria-hidden 
        />
      </span>
      <span className="min-w-0 truncate leading-snug">{label}</span>
    </Link>
  );
}

function DesktopNavGroup({
  group,
  pathname,
}: {
  group: NavGroup;
  pathname: string | null;
}) {
  const GroupIcon = group.icon;
  const groupActive = isGroupActive(group, pathname);
  const [open, setOpen] = useState(groupActive);

  return (
    <div>
      <button
        type="button"
        onClick={() => setOpen((v) => !v)}
        aria-expanded={open}
        className={cn(
          "group flex w-full items-center gap-3 rounded-lg px-3 py-2 text-sm font-semibold transition-colors",
          groupActive ? "text-primary" : "text-muted-foreground hover:bg-[#0946aa] hover:text-white"
        )}
      >
        <span
          className={cn(
            "flex h-8 w-8 shrink-0 items-center justify-center rounded-md transition-colors",
            groupActive
              ? "bg-primary/10"
              : "bg-muted/50 group-hover:bg-white/20"
          )}
        >
          <GroupIcon 
            className={cn(
              "h-4 w-4 transition-colors",
              groupActive ? "text-primary" : "text-muted-foreground group-hover:text-white"
            )} 
            aria-hidden 
          />
        </span>
        <span className="min-w-0 flex-1 truncate text-left leading-snug">{group.label}</span>
        <ChevronDown
          className={cn(
            "h-4 w-4 shrink-0 transition-all duration-200",
            open && "rotate-180",
            !groupActive && "group-hover:text-white"
          )}
          aria-hidden
        />
      </button>
      {open && (
        <div className="mt-0.5 space-y-0.5">
          {group.children.map((child) => (
            <DesktopNavLink
              key={child.href}
              href={child.href}
              label={child.label}
              icon={child.icon}
              active={isNavActive(child.href, pathname)}
              sub
            />
          ))}
        </div>
      )}
    </div>
  );
}

function MobileNavLink({
  href,
  label,
  icon: Icon,
  active,
}: {
  href: string;
  label: string;
  icon: LucideIcon;
  active: boolean;
}) {
  return (
    <Link
      href={href}
      aria-current={active ? "page" : undefined}
      className={cn(
        "inline-flex shrink-0 items-center gap-1.5 rounded-full border px-3 py-1.5 text-xs font-medium transition-colors",
        active
          ? "border-primary/60 bg-primary/10 text-primary"
          : "border-border/60 bg-card text-muted-foreground hover:bg-[#0946aa] hover:text-white hover:border-[#0946aa]"
      )}
    >
      <Icon 
        className={cn(
          "h-3.5 w-3.5",
          active ? "text-primary" : ""
        )} 
        aria-hidden 
      />
      <span className="max-w-[10rem] truncate">{label}</span>
    </Link>
  );
}

export function AdminSidebar() {
  const pathname = usePathname();

  return (
    <>
      {/* Barre mobile : pills horizontales */}
      <div
        className="border-t border-border/50 md:hidden"
        role="navigation"
        aria-label="Menu administration"
      >
        <div className="flex gap-2 overflow-x-auto px-3 py-2.5 [scrollbar-width:none] [&::-webkit-scrollbar]:hidden">
          {NAV_ITEMS.map((item) => (
            <MobileNavLink
              key={item.href}
              href={item.href}
              label={item.shortLabel ?? item.label}
              icon={item.icon}
              active={isNavActive(item.href, pathname)}
            />
          ))}
          {DEPENSE_GROUP.children.map((child) => (
            <MobileNavLink
              key={child.href}
              href={child.href}
              label={child.shortLabel ?? child.label}
              icon={child.icon}
              active={isNavActive(child.href, pathname)}
            />
          ))}
          {RAPPORT_GROUP.children.map((child) => (
            <MobileNavLink
              key={child.href}
              href={child.href}
              label={child.shortLabel ?? child.label}
              icon={child.icon}
              active={isNavActive(child.href, pathname)}
            />
          ))}
        </div>
      </div>

      {/* Sidebar desktop */}
      <nav
        className="hidden flex-1 flex-col md:flex"
        aria-label="Menu administration"
      >
        <div className="flex-1 px-3 py-4 md:px-4 md:py-5">
          <div className="space-y-1">
            {NAV_ITEMS.map((item) => (
              <DesktopNavLink
                key={item.href}
                href={item.href}
                label={item.label}
                icon={item.icon}
                active={isNavActive(item.href, pathname)}
              />
            ))}
            <DesktopNavGroup group={DEPENSE_GROUP} pathname={pathname} />
            <div className="py-1">
              <div className="mx-3 border-t border-border/40" />
            </div>
            <DesktopNavGroup group={RAPPORT_GROUP} pathname={pathname} />
          </div>
        </div>
      </nav>
    </>
  );
}
