import { ChevronsDown, ChevronsUp } from "lucide-react";
import type { JSX } from "react";
import { Button } from "./button";
import { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger } from "./tooltip";
import type { JsonExpansionPolicy } from "./json-viewer-bulk";

/**
 * Toggle the JSON bulk-expansion state of a request body. Split into its own
 * module (instead of living next to `JsonViewer`) so the bundler can put
 * `JsonViewer` into a lazy chunk — the static import of the toolbar button
 * used to drag the whole viewer into the main bundle.
 */
export function JsonExpansionButton({
  policy,
  isExpanded,
  isPending,
  onToggle,
}: {
  policy: JsonExpansionPolicy | null;
  isExpanded: boolean;
  isPending: boolean;
  onToggle: () => void;
}): JSX.Element | null {
  if (policy === null) return null;

  const label = isPending ? "Updating..." : isExpanded ? "Collapse all" : "Expand all";
  const tooltip = isExpanded ? "Collapse all JSON nodes" : "Expand all JSON nodes";

  return (
    <TooltipProvider>
      <Tooltip>
        <TooltipTrigger asChild>
          <Button
            variant="outline"
            size="sm"
            className="h-8 text-xs"
            onClick={(e) => {
              e.stopPropagation();
              onToggle();
            }}
            disabled={isPending}
            aria-pressed={isExpanded}
          >
            {isExpanded ? (
              <ChevronsUp className="size-3.5 mr-1" />
            ) : (
              <ChevronsDown className="size-3.5 mr-1" />
            )}
            {label}
          </Button>
        </TooltipTrigger>
        <TooltipContent>{tooltip}</TooltipContent>
      </Tooltip>
    </TooltipProvider>
  );
}
