import { useQuery } from "@tanstack/react-query";
import { Bot, PanelRightClose, PanelRightOpen } from "lucide-react";

import { getServerHealth } from "../api/client";
import { Button } from "../components/common/Button";
import { useLayoutStore } from "../stores/layoutStore";

const pageTitles = {
  agent: "Agent",
  projects: "Projects",
  settings: "Settings",
};

export function TopBar() {
  const activeNav = useLayoutStore((state) => state.activeNav);
  const isAgentSidebarOpen = useLayoutStore((state) => state.isAgentSidebarOpen);
  const toggleAgentSidebar = useLayoutStore((state) => state.toggleAgentSidebar);
  const healthQuery = useQuery({
    queryKey: ["server-health"],
    queryFn: getServerHealth,
    staleTime: 10_000,
  });

  const health = healthQuery.data ?? { ok: false, label: "checking" };

  return (
    <header className="top-bar">
      <div>
        <p>NomadCode Web</p>
        <h1>{pageTitles[activeNav]}</h1>
      </div>
      <div className="top-bar__actions">
        <span className={health.ok ? "connection-badge is-online" : "connection-badge"}>
          <span aria-hidden="true" />
          Core {health.label}
        </span>
        <Button
          type="button"
          variant="secondary"
          size="sm"
          icon={isAgentSidebarOpen ? <PanelRightClose size={16} aria-hidden="true" /> : <PanelRightOpen size={16} aria-hidden="true" />}
          onClick={toggleAgentSidebar}
        >
          <span className="hide-on-small">{isAgentSidebarOpen ? "Hide Agent" : "Show Agent"}</span>
          <span className="show-on-small">Agent</span>
        </Button>
        <Button type="button" variant="ghost" size="icon" aria-label="Agent quick status" icon={<Bot size={18} aria-hidden="true" />} />
      </div>
    </header>
  );
}
