import { AgentToggleButton } from "@agent-native/core/client/agent-chat";
import { RunsTray } from "@agent-native/core/client/progress";
import { IconLayoutSidebar } from "@tabler/icons-react";
import { useLocation, useNavigate } from "react-router";

import { Button } from "../ui/button";
import { useHeaderTitle, useHeaderActions } from "./HeaderActions";

const pageTitles: Record<string, string> = {
  "/": "Overview",
  "/overview": "Overview",
  "/vault": "Vault",
  "/integrations": "Integrations",
  "/workspace": "Resources",
  "/messaging": "Messaging",
  "/agents": "Agents",
  "/destinations": "Destinations",
  "/identities": "Identities",
  "/approvals": "Approvals",
  "/automations": "Automations",
  "/audit": "Audit",
  "/dreams": "Dreams",
  "/thread-debug": "Thread Debug",
  "/transactional-email": "Transactional email",
  "/settings": "Settings",
};

function resolveTitle(pathname: string): string {
  if (pathname === "/admin" || pathname === "/admin/") return "Admin";
  if (pathname.startsWith("/admin/")) {
    const adminPath = pathname.slice("/admin".length);
    return pageTitles[adminPath] ?? "Admin";
  }
  if (pageTitles[pathname]) return pageTitles[pathname];

  if (pathname.startsWith("/extensions")) return "Extensions";

  return "Dispatch";
}

export function Header({
  onOpenMobile,
  showAgentToggle = true,
}: {
  onOpenMobile?: () => void;
  showAgentToggle?: boolean;
}) {
  const location = useLocation();
  const navigate = useNavigate();
  const title = useHeaderTitle();
  const actions = useHeaderActions();

  function openRunThread(threadId: string) {
    navigate("/chat", {
      state: {
        dispatchThread: {
          id: `${Date.now()}-${threadId}`,
          threadId,
        },
      },
    });
    window.requestAnimationFrame(() => {
      window.dispatchEvent(
        new CustomEvent("agent-chat:open-thread", {
          detail: { threadId },
        }),
      );
    });
  }

  return (
    <header className="flex h-12 shrink-0 items-center gap-3 border-b border-border bg-background px-4 lg:px-6">
      {onOpenMobile ? (
        <Button
          variant="ghost"
          size="icon"
          className="h-8 w-8 lg:hidden cursor-pointer"
          onClick={onOpenMobile}
          aria-label="Open navigation"
        >
          <IconLayoutSidebar />
        </Button>
      ) : null}
      <div className="flex items-center gap-3 flex-1 min-w-0">
        {title ?? (
          <h1 className="text-lg font-semibold tracking-tight truncate">
            {resolveTitle(location.pathname)}
          </h1>
        )}
      </div>
      <div className="flex items-center gap-2 shrink-0">
        {actions}
        <RunsTray limit={8} onOpenThread={openRunThread} />
        {showAgentToggle ? (
          <AgentToggleButton className="h-8 w-8 rounded-md hover:bg-accent" />
        ) : null}
      </div>
    </header>
  );
}
