import type { ComponentProps } from 'react'
import { type HandleProps, Position } from '@xyflow/react'
import { cn } from '@/lib/utils'
import { BaseHandle } from './base-handle'

const flexDirections: Record<string, string> = {
  [Position.Top]: 'flex-col',
  [Position.Right]: 'flex-row-reverse justify-end',
  [Position.Bottom]: 'flex-col-reverse justify-end',
  [Position.Left]: 'flex-row',
}

export function LabeledHandle({
  className,
  labelClassName,
  handleClassName,
  title,
  position,
  ...props
}: HandleProps &
  ComponentProps<'div'> & {
    title: string
    handleClassName?: string
    labelClassName?: string
  }) {
  const { ref, ...handleProps } = props
  return (
    <div
      title={title}
      className={cn('relative flex items-center', flexDirections[position], className)}
      ref={ref}
    >
      <BaseHandle position={position} className={handleClassName} {...handleProps} />
      <label className={cn('text-muted-foreground text-[10px] font-mono px-1.5', labelClassName)}>
        {title}
      </label>
    </div>
  )
}
