import { useState, useEffect } from "react";
import { useLocation, useNavigate } from "react-router-dom";
import { LogOut, User, Bell } from "lucide-react";
import { Button } from "@/components/ui/button";
import { useAuth } from "@/auth/AuthProvider";
import { useCosts } from "@/api/costs";

const breadcrumbMap: Record<string, string> = {
  "/": "Vue d'ensemble",
  "/policies": "Politiques de routage",
  "/users": "Utilisateurs",
  "/providers": "Fournisseurs IA",
  "/alerts": "Alertes Budget",
  "/logs": "Journaux d'audit",
  "/settings": "Paramètres",
  "/playground": "Playground IA",
  "/security": "Sécurité RSSI",
  "/costs": "Coûts IA",
  "/compliance": "Conformité RGPD / AI Act",
};

const STORAGE_KEY = "veylant_budget_alerts";

interface BudgetAlert {
  id: string;
  threshold: number;
}

function loadAlerts(): BudgetAlert[] {
  try {
    return JSON.parse(localStorage.getItem(STORAGE_KEY) ?? "[]");
  } catch {
    return [];
  }
}

export function Header() {
  const location = useLocation();
  const navigate = useNavigate();
  const { user, logout } = useAuth();
  const title = breadcrumbMap[location.pathname] ?? "Dashboard";

  const [alerts] = useState<BudgetAlert[]>(loadAlerts);
  const { data: costData } = useCosts({}, 60_000);
  const totalCost = costData?.data.reduce((s, c) => s + c.total_cost_usd, 0) ?? 0;
  const triggeredCount = alerts.filter((a) => totalCost >= a.threshold).length;

  return (
    <header className="h-14 border-b bg-card flex items-center justify-between px-6 shrink-0">
      <h1 className="text-base font-semibold">{title}</h1>

      <div className="flex items-center gap-3">
        {/* Bell badge — E8-13 */}
        <Button
          variant="ghost"
          size="icon"
          onClick={() => navigate("/alerts")}
          title="Alertes budget"
          className="relative"
        >
          <Bell className="h-4 w-4" />
          {triggeredCount > 0 && (
            <span className="absolute -top-0.5 -right-0.5 h-4 w-4 rounded-full bg-destructive text-destructive-foreground text-[10px] font-bold flex items-center justify-center leading-none">
              {triggeredCount > 9 ? "9+" : triggeredCount}
            </span>
          )}
        </Button>

        <div className="flex items-center gap-2 text-sm text-muted-foreground">
          <User className="h-4 w-4" />
          <span className="hidden sm:inline">{user?.name ?? user?.email}</span>
          {user?.roles[0] && (
            <span className="text-xs bg-secondary px-1.5 py-0.5 rounded capitalize">
              {user.roles[0]}
            </span>
          )}
        </div>
        <Button variant="ghost" size="icon" onClick={logout} title="Se déconnecter">
          <LogOut className="h-4 w-4" />
        </Button>
      </div>
    </header>
  );
}
