"use client";

import Link from "next/link";
import { usePathname } from "next/navigation";
import { useSession } from "next-auth/react";
import {
  BarChart3, FileText, ClipboardList, Receipt, ArrowLeftRight, BookOpen, Book,
  Scale, PieChart, Users, Building2, Landmark, Settings, CreditCard, Menu, Repeat,
  PackageCheck, ShieldCheck, Package, Wrench, ChevronRight,
} from "lucide-react";
import { cn } from "@/lib/utils";
import { Sheet, SheetContent, SheetTrigger } from "@/components/ui/sheet";
import { Button } from "@/components/ui/button";
import { useOrganization } from "@/hooks/use-organization";

const NAV_SECTIONS = [
  {
    items: [
      { label: "Tableau de bord", href: "/tableau-de-bord", icon: BarChart3 },
    ],
  },
  {
    group: "Finances",
    items: [
      { label: "Factures",       href: "/factures",              icon: FileText     },
      { label: "Récurrentes",    href: "/factures/recurrentes",  icon: Repeat       },
      { label: "Devis",          href: "/devis",                 icon: ClipboardList },
      { label: "Livraisons",     href: "/livraisons",            icon: PackageCheck  },
      { label: "Interventions",  href: "/interventions",         icon: Wrench        },
      { label: "Dépenses",       href: "/depenses",              icon: Receipt       },
      { label: "Transactions",   href: "/transactions",          icon: ArrowLeftRight},
    ],
  },
  {
    group: "Comptabilité",
    items: [
      { label: "Journal",     href: "/comptabilite/journal",     icon: BookOpen },
      { label: "Grand livre", href: "/comptabilite/grand-livre", icon: Book     },
      { label: "Balance",     href: "/comptabilite/balance",     icon: Scale    },
    ],
  },
  {
    group: "Rapports",
    items: [
      { label: "Rapports", href: "/rapports", icon: PieChart },
    ],
  },
  {
    group: "Administration",
    items: [
      { label: "Clients",      href: "/clients",      icon: Users     },
      { label: "Fournisseurs", href: "/fournisseurs", icon: Building2 },
      { label: "Banque",       href: "/banque",       icon: Landmark  },
      { label: "Produits",     href: "/produits",     icon: Package   },
    ],
  },
];

const BOTTOM_NAV = [
  { label: "Paramètres",  href: "/parametres", icon: Settings   },
  { label: "Abonnement",  href: "/abonnement", icon: CreditCard },
];

function NavItem({
  label,
  href,
  icon: Icon,
  active,
}: {
  label: string;
  href: string;
  icon: React.ElementType;
  active: boolean;
}) {
  return (
    <Link
      href={href}
      className={cn(
        "group relative flex items-center gap-2.5 rounded-md px-3 py-2 text-base font-medium transition-all duration-150",
        active
          ? "bg-sidebar-accent text-sidebar-foreground"
          : "text-sidebar-foreground/45 hover:bg-sidebar-accent/60 hover:text-sidebar-foreground/80"
      )}
    >
      {/* Indicateur actif — barre gauche */}
      {active && (
        <span className="absolute left-0 top-1/2 -translate-y-1/2 h-5 w-[3px] rounded-r-full bg-sidebar-primary" />
      )}

      <Icon
        className={cn(
          "h-4 w-4 shrink-0 transition-colors",
          active
            ? "text-sidebar-primary"
            : "text-sidebar-foreground/30 group-hover:text-sidebar-foreground/55"
        )}
      />
      <span className="truncate flex-1">{label}</span>
      {active && (
        <ChevronRight className="h-3 w-3 text-sidebar-primary/50 shrink-0" />
      )}
    </Link>
  );
}

function OrgInitials({ name }: { name: string }) {
  const parts = name.trim().split(/\s+/).filter(Boolean);
  const initials = parts.length >= 2
    ? (parts[0][0] + parts[parts.length - 1][0]).toUpperCase()
    : name.slice(0, 2).toUpperCase();
  return <span>{initials}</span>;
}

function SidebarInner({ pathname }: { pathname: string }) {
  const { organization } = useOrganization();
  const { data: session } = useSession();
  const isSuperAdmin = (session?.user as any)?.isSuperAdmin;
  const orgName = organization?.name ?? "NextCRM";

  return (
    <div className="flex h-full flex-col overflow-hidden">

      {/* ── Logo & org ── */}
      <div className="flex items-center gap-3 px-4 py-[18px] border-b border-sidebar-border shrink-0">
        {/* Avatar organisation */}
        <div className="h-8 w-8 rounded-lg bg-gradient-to-br from-sidebar-primary to-indigo-400/80 flex items-center justify-center text-white text-[11px] font-bold tracking-wide shrink-0 shadow-sm">
          <OrgInitials name={orgName} />
        </div>
        <div className="min-w-0 flex-1">
          <p className="truncate text-base font-semibold text-sidebar-foreground leading-tight">
            {orgName}
          </p>
          <p className="text-[11px] text-sidebar-foreground/40 uppercase tracking-[0.1em] mt-0.5 font-medium">
            Comptabilité
          </p>
        </div>
      </div>

      {/* ── Navigation principale ── */}
      <nav className="flex-1 overflow-y-auto scrollbar-hide px-2.5 py-3 space-y-4">
        {NAV_SECTIONS.map((section, i) => (
          <div key={i}>
            {section.group && (
              <p className="mb-1.5 px-3 text-[11px] font-semibold uppercase tracking-[0.12em] text-sidebar-foreground/35 select-none">
                {section.group}
              </p>
            )}
            <div className="space-y-[2px]">
              {section.items.map((item) => (
                <NavItem
                  key={item.href}
                  {...item}
                  active={
                    pathname === item.href ||
                    (item.href !== "/tableau-de-bord" && pathname.startsWith(item.href))
                  }
                />
              ))}
            </div>
          </div>
        ))}
      </nav>

      {/* ── Navigation bas de page ── */}
      <div className="shrink-0 border-t border-sidebar-border px-2.5 py-3 space-y-[2px]">
        {BOTTOM_NAV.map((item) => (
          <NavItem
            key={item.href}
            {...item}
            active={pathname.startsWith(item.href)}
          />
        ))}
        {isSuperAdmin && (
          <NavItem
            label="Admin plateforme"
            href="/admin"
            icon={ShieldCheck}
            active={pathname.startsWith("/admin")}
          />
        )}
      </div>
    </div>
  );
}

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

  return (
    <>
      {/* Desktop */}
      <aside className="hidden lg:flex h-screen w-56 shrink-0 flex-col bg-sidebar border-r border-sidebar-border sticky top-0 overflow-hidden">
        <SidebarInner pathname={pathname} />
      </aside>

      {/* Mobile */}
      <Sheet>
        <SheetTrigger asChild>
          <Button
            variant="ghost"
            size="icon"
            className="lg:hidden fixed top-3 left-3 z-50 h-9 w-9 bg-background/90 backdrop-blur-md border border-border/60 shadow-sm"
          >
            <Menu className="h-4 w-4" />
          </Button>
        </SheetTrigger>
        <SheetContent
          side="left"
          className="w-56 p-0 bg-sidebar border-sidebar-border"
        >
          <SidebarInner pathname={pathname} />
        </SheetContent>
      </Sheet>
    </>
  );
}
