import { memo } from "react"
import { Handle, Position, type NodeProps } from "@xyflow/react"
import { ArrowRight, X } from "lucide-react"

import { cn } from "@/lib/utils"
import { StageNodeData } from "./types"

/**
 * Stage card (docs/21-FRONTEND-PHASE2.md §2): name, role label chip, estimated minutes,
 * input count → output count. Selecting it opens the stage editor panel (handled by the
 * parent page via onNodeClick, not here) — the same delete affordance also lives there
 * ("Delete stage" button); this inline × is a faster path once a stage is already selected.
 */
function StageNode({ data, selected }: NodeProps & { data: StageNodeData }) {
  const disconnected = data.disconnected

  return (
    <div
      className={cn(
        "relative w-56 rounded-2xl bg-card p-3 shadow-sm ring-2 transition-all",
        // `focused` wins over `selected`: it marks the stage the server's 422 named, and the
        // click that selects a node must not hide the reason the save failed.
        data.focused ? "ring-destructive" : selected ? "ring-primary" : "ring-foreground/10",
        disconnected && "opacity-40"
      )}
    >
      <Handle type="target" position={Position.Left} className="!bg-primary !size-2.5" />

      {selected && data.onDelete && (
        <button
          type="button"
          aria-label="Delete stage"
          title="Delete stage"
          className="nodrag absolute -top-2.5 -right-2.5 flex size-5 items-center justify-center rounded-full bg-destructive text-white shadow-sm hover:bg-destructive/90"
          onClick={(e) => {
            e.stopPropagation()
            data.onDelete?.()
          }}
        >
          <X className="size-3" />
        </button>
      )}

      <div className="flex items-start justify-between gap-2">
        <p className="min-w-0 truncate text-sm font-bold text-foreground">{data.name || "Untitled stage"}</p>
        {data.roleLabel && (
          <span className="shrink-0 rounded-full bg-primary/10 px-2 py-0.5 text-xs font-medium text-primary">
            {data.roleLabel}
          </span>
        )}
      </div>

      <p className="mt-1 text-xs text-muted-foreground">{data.estimatedMinutes} min</p>

      <div className="mt-2 flex items-center gap-1.5 text-xs text-muted-foreground">
        <span>{data.inputs.length} in</span>
        <ArrowRight className="size-3" />
        <span>{data.outputs.length} out</span>
      </div>

      {disconnected && <p className="mt-1.5 text-xs font-medium text-warning">Disconnected</p>}

      <Handle type="source" position={Position.Right} className="!bg-primary !size-2.5" />
    </div>
  )
}

export default memo(StageNode)
