import { Menu, Sun, Moon, Monitor, LogOut } from "lucide-react";
import { Button } from "@/components/ui/button";
import { useSseStatus } from "@/lib/sse-context";
import { useTheme } from "@/lib/theme";
import { useAuth } from "@/lib/auth-context";
import { cn } from "@/lib/utils";

interface HeaderProps {
  onMenuClick: () => void;
}

export function Header({ onMenuClick }: HeaderProps) {
  const sseStatus = useSseStatus();
  const { theme, cycleTheme } = useTheme();
  const auth = useAuth();

  const ThemeIcon = theme === "light" ? Sun : theme === "dark" ? Moon : Monitor;
  const themeLabel =
    theme === "light" ? "Claro" : theme === "dark" ? "Oscuro" : "Sistema";

  async function handleSignOut() {
    await auth.signOut();
    window.location.href = "/login";
  }

  return (
    <header className="flex h-14 items-center gap-4 border-b px-4">
      <Button
        variant="ghost"
        size="icon"
        className="md:hidden"
        onClick={onMenuClick}
      >
        <Menu className="size-5" />
      </Button>
      <div className="flex-1" />
      <div className="flex items-center gap-1.5">
        {auth.isAuthenticated && (
          <>
            <span className="hidden text-sm text-muted-foreground sm:inline">
              {auth.session?.user.email}
            </span>
            <Button
              variant="ghost"
              size="icon"
              onClick={handleSignOut}
              title="Cerrar sesión"
            >
              <LogOut className="size-4" />
            </Button>
          </>
        )}
        <Button
          variant="ghost"
          size="icon"
          onClick={cycleTheme}
          title={`Tema: ${themeLabel} (Cmd+D)`}
        >
          <ThemeIcon className="size-4" />
        </Button>
        <span
          className={cn(
            "size-2 rounded-full",
            sseStatus === "connected" && "bg-emerald-500",
            sseStatus === "connecting" && "bg-amber-500 animate-pulse",
            sseStatus === "disconnected" && "bg-red-500",
          )}
        />
        <span className="text-xs text-muted-foreground">
          {sseStatus === "connected" && "Live"}
          {sseStatus === "connecting" && "Conectando..."}
          {sseStatus === "disconnected" && "Desconectado"}
        </span>
      </div>
    </header>
  );
}
