import { memo } from "react"
import { Handle, Position, type NodeProps } from "@xyflow/react"

import { cn } from "@/lib/utils"

export interface LineHeaderData extends Record<string, unknown> {
  templateId: number
  /** The template's `code` (e.g. `PT-CHAIR`). Templates carry a code; only runs get a doc no. */
  code: string
  name: string
  status: "Active" | "Inactive"
  activeRunCount: number
}

/** Row label docked at the left of each production line — the template itself. */
function LineHeaderNode({ data }: NodeProps & { data: LineHeaderData }) {
  return (
    <div className="flex w-56 flex-col gap-1.5 rounded-2xl bg-card p-3 shadow-sm ring-1 ring-foreground/10">
      <div className="flex items-center justify-between gap-2">
        <span className="truncate text-xs font-medium text-muted-foreground">{data.code}</span>
        <span
          className={cn(
            "shrink-0 rounded-full px-2 py-0.5 text-xs font-medium",
            data.status === "Active" ? "bg-success/10 text-success" : "bg-muted text-muted-foreground"
          )}
        >
          {data.status}
        </span>
      </div>
      <p className="truncate text-sm font-bold text-foreground">{data.name}</p>
      {data.activeRunCount > 0 && (
        <span className="w-fit rounded-full bg-warning/10 px-2 py-0.5 text-xs font-medium text-warning">
          {data.activeRunCount} in progress
        </span>
      )}
      <Handle type="source" position={Position.Right} className="!bg-primary !size-2.5" />
    </div>
  )
}

export interface LineStageData extends Record<string, unknown> {
  templateId: number
  name: string
}

/** One stage on a production line — read-only, purely a visual chip on the overview canvas. */
function LineStageNode({ data }: NodeProps & { data: LineStageData }) {
  return (
    <div className="w-36 rounded-xl bg-primary/10 px-3 py-2.5 text-center shadow-sm ring-1 ring-primary/20">
      <Handle type="target" position={Position.Left} className="!bg-primary !size-2.5" />
      <p className="truncate text-sm font-semibold text-primary">{data.name}</p>
      <Handle type="source" position={Position.Right} className="!bg-primary !size-2.5" />
    </div>
  )
}

export const LineHeaderNodeComponent = memo(LineHeaderNode)
export const LineStageNodeComponent = memo(LineStageNode)
