"use client";

import { usePathname, useRouter } from "next/navigation";
import Link from "next/link";
import { useSession, signOut } from "next-auth/react";
import { useTheme } from "next-themes";
import {
  Bell, Sun, Moon, ChevronRight, Plus, User, Settings, LogOut,
} from "lucide-react";
import { Button } from "@/components/ui/button";
import { Avatar, AvatarFallback, AvatarImage } from "@/components/ui/avatar";
import {
  DropdownMenu,
  DropdownMenuContent,
  DropdownMenuItem,
  DropdownMenuLabel,
  DropdownMenuSeparator,
  DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu";
import { cn, getInitials } from "@/lib/utils";

const ROUTE_LABELS: Record<string, string> = {
  "tableau-de-bord": "Tableau de bord",
  factures:          "Factures",
  nouvelle:          "Nouvelle facture",
  recurrentes:       "Récurrentes",
  devis:             "Devis",
  livraisons:        "Livraisons",
  interventions:     "Interventions",
  depenses:          "Dépenses",
  transactions:      "Transactions",
  comptabilite:      "Comptabilité",
  journal:           "Journal",
  "grand-livre":     "Grand livre",
  balance:           "Balance",
  rapports:          "Rapports",
  clients:           "Clients",
  fournisseurs:      "Fournisseurs",
  banque:            "Banque",
  produits:          "Produits",
  parametres:        "Paramètres",
  abonnement:        "Abonnement",
  utilisateurs:      "Utilisateurs",
  admin:             "Administration",
};

function Breadcrumb({ pathname }: { pathname: string }) {
  const segments = pathname.split("/").filter(Boolean);
  if (segments.length === 0) return null;

  return (
    <nav className="flex items-center gap-1">
      {segments.map((seg, i) => {
        const isLast = i === segments.length - 1;
        const label = ROUTE_LABELS[seg] ?? seg;
        const href = "/" + segments.slice(0, i + 1).join("/");

        return (
          <span key={i} className="flex items-center gap-1">
            {i > 0 && (
              <ChevronRight className="h-3 w-3 text-muted-foreground/30 shrink-0" />
            )}
            {isLast ? (
              <span className="text-[13px] font-semibold text-foreground/90 tracking-tight">
                {label}
              </span>
            ) : (
              <Link
                href={href}
                className="text-[13px] text-muted-foreground/60 hover:text-foreground/70 transition-colors"
              >
                {label}
              </Link>
            )}
          </span>
        );
      })}
    </nav>
  );
}

export function Header() {
  const pathname = usePathname();
  const router = useRouter();
  const { data: session } = useSession();
  const { theme, setTheme } = useTheme();
  const user = session?.user;

  return (
    <header className="sticky top-0 z-30 flex h-12 items-center gap-3 border-b border-border/60 bg-background/75 backdrop-blur-md px-4 lg:px-5">

      {/* Breadcrumb */}
      <div className="flex-1 pl-10 lg:pl-0 min-w-0">
        <Breadcrumb pathname={pathname} />
      </div>

      <div className="flex items-center gap-1.5">

        {/* CTA Nouvelle facture */}
        <Button
          size="sm"
          className="hidden sm:inline-flex h-7 gap-1.5 text-xs px-3 rounded-md shadow-none"
          onClick={() => router.push("/factures/nouvelle")}
        >
          <Plus className="h-3 w-3" />
          Nouvelle facture
        </Button>

        {/* Notifications */}
        <Button
          variant="ghost"
          size="icon"
          className="relative h-7 w-7 rounded-md text-muted-foreground hover:text-foreground hover:bg-accent/60"
        >
          <Bell className="h-3.5 w-3.5" />
          {/* Badge */}
          <span className="absolute top-0.5 right-0.5 h-1.5 w-1.5 rounded-full bg-primary ring-1 ring-background" />
        </Button>

        {/* Toggle thème */}
        <Button
          variant="ghost"
          size="icon"
          className="h-7 w-7 rounded-md text-muted-foreground hover:text-foreground hover:bg-accent/60"
          onClick={() => setTheme(theme === "dark" ? "light" : "dark")}
        >
          <Sun className="h-3.5 w-3.5 rotate-0 scale-100 transition-transform dark:-rotate-90 dark:scale-0" />
          <Moon className="absolute h-3.5 w-3.5 rotate-90 scale-0 transition-transform dark:rotate-0 dark:scale-100" />
        </Button>

        {/* Séparateur visuel */}
        <div className="h-4 w-px bg-border/60 mx-0.5" />

        {/* Avatar & Dropdown */}
        <DropdownMenu>
          <DropdownMenuTrigger asChild>
            <Button
              variant="ghost"
              className="h-7 gap-2 px-2 rounded-md hover:bg-accent/60 text-muted-foreground hover:text-foreground"
            >
              <Avatar className="h-5 w-5">
                <AvatarImage src={user?.image ?? undefined} />
                <AvatarFallback className="text-[9px] font-semibold bg-primary/15 text-primary">
                  {getInitials(user?.name ?? user?.email ?? "U")}
                </AvatarFallback>
              </Avatar>
              <span className="hidden sm:block text-[12px] font-medium max-w-[100px] truncate">
                {user?.name?.split(" ")[0] ?? user?.email}
              </span>
            </Button>
          </DropdownMenuTrigger>
          <DropdownMenuContent align="end" className="w-52">
            <DropdownMenuLabel className="font-normal py-2">
              <div className="flex flex-col gap-0.5">
                <p className="text-[13px] font-semibold text-foreground">{user?.name}</p>
                <p className="text-[11px] text-muted-foreground truncate">{user?.email}</p>
              </div>
            </DropdownMenuLabel>
            <DropdownMenuSeparator />
            <DropdownMenuItem asChild>
              <Link href="/parametres" className="text-[13px]">
                <User className="mr-2 h-3.5 w-3.5" />
                Profil
              </Link>
            </DropdownMenuItem>
            <DropdownMenuItem asChild>
              <Link href="/parametres" className="text-[13px]">
                <Settings className="mr-2 h-3.5 w-3.5" />
                Paramètres
              </Link>
            </DropdownMenuItem>
            <DropdownMenuSeparator />
            <DropdownMenuItem
              className="text-destructive focus:text-destructive text-[13px]"
              onClick={() => signOut({ callbackUrl: "/connexion" })}
            >
              <LogOut className="mr-2 h-3.5 w-3.5" />
              Déconnexion
            </DropdownMenuItem>
          </DropdownMenuContent>
        </DropdownMenu>
      </div>
    </header>
  );
}
