"use client";

import { useCallback } from "react";
import { useReactFlow, getNodesBounds } from "@xyflow/react";

import { Button } from "@turbostarter/ui-web/button";
import { Icons } from "@turbostarter/ui-web/icons";
import {
  Tooltip,
  TooltipContent,
  TooltipProvider,
  TooltipTrigger,
} from "@turbostarter/ui-web/tooltip";

import { useGraphStore } from "../../stores/useGraphStore";

import type { Node } from "@xyflow/react";

const HOVER_ACTIONS = [
  {
    key: "transform",
    icon: Icons.RefreshCcw,
    label: "Transform",
    getText: (label: string, type: string) =>
      `Transform this ${type} "${label}" into `,
  },
  {
    key: "split",
    icon: Icons.GitBranch,
    label: "Split",
    getText: (label: string, _type: string) => `Split "${label}" into `,
  },
  {
    key: "merge",
    icon: Icons.Workflow,
    label: "Merge",
    getText: (label: string, _type: string) => `Merge "${label}" with `,
  },
  {
    key: "explain",
    icon: Icons.Info,
    label: "Explain",
    getText: (label: string, _type: string) =>
      `Explain this element: "${label}"`,
  },
  {
    key: "annotate",
    icon: Icons.MessageSquare,
    label: "Annotate",
    getText: (label: string, _type: string) => `Annotate "${label}": `,
  },
] as const;

export { HOVER_ACTIONS };

interface HoverAffordancesProps {
  nodeId: string;
}

export function HoverAffordances({ nodeId }: HoverAffordancesProps) {
  const { getNodes, getViewport } = useReactFlow();
  const node = getNodes().find((n: Node) => n.id === nodeId);

  const handleAction = useCallback(
    (action: (typeof HOVER_ACTIONS)[number]) => {
      // Look up node fresh inside callback to avoid stale closure
      const currentNode = getNodes().find((n: Node) => n.id === nodeId);
      if (!currentNode) return;
      const data = currentNode.data as { label?: string; type?: string };
      const label = data.label ?? currentNode.id;
      const type = data.type ?? "element";
      const text = action.getText(label, type);

      const store = useGraphStore.getState();
      store.setSelectedNodeIds([nodeId]);
      store.setPrefillChat(nodeId, text);
    },
    [nodeId, getNodes],
  );

  if (!node) return null;

  // Use getNodesBounds for absolute coordinates — node.position is relative
  // to parent for nested nodes (e.g., BPMN activities inside pools/lanes)
  const bounds = getNodesBounds([node]);
  const { x, y, zoom } = getViewport();
  const screenX = bounds.x * zoom + x;
  const screenY = bounds.y * zoom + y;
  const nodeWidth = bounds.width * zoom;

  return (
    <TooltipProvider delayDuration={0}>
      <div
        className="hover-affordances absolute z-50 pointer-events-auto"
        style={{
          left: screenX + nodeWidth / 2,
          top: screenY - 8,
          transform: "translate(-50%, -100%)",
        }}
        role="toolbar"
        aria-label={`AI actions for ${(node.data as { label?: string }).label ?? node.id}`}
      >
        <div className="flex items-center gap-0.5 rounded-lg border border-border bg-[var(--canvas-bg)]/90 px-1 py-0.5 shadow-md backdrop-blur-sm">
          {HOVER_ACTIONS.map((action) => (
            <Tooltip key={action.key}>
              <TooltipTrigger asChild>
                <Button
                  size="icon"
                  variant="ghost"
                  className="size-7"
                  onClick={() => handleAction(action)}
                >
                  <action.icon className="size-3.5" />
                </Button>
              </TooltipTrigger>
              <TooltipContent side="top" className="text-xs">
                {action.label}
              </TooltipContent>
            </Tooltip>
          ))}
        </div>
      </div>
    </TooltipProvider>
  );
}
