import { forwardRef } from 'react'
import type { HTMLAttributes, ReactNode } from 'react'
import { cn } from '@/lib/utils'
import { CloseLine } from '../basic/icons-inline'

export interface ChatContextTagProps extends Omit<HTMLAttributes<HTMLSpanElement>, 'children'> {
  label: ReactNode
  icon?: ReactNode
  onRemove?: () => void
  removeLabel?: string
}

export const ChatContextTag = forwardRef<HTMLSpanElement, ChatContextTagProps>(
  ({ label, icon, onRemove, removeLabel = 'Remove context', className, ...props }, ref) => (
    <span
      ref={ref}
      data-slot="chat-context-tag"
      className={cn(
        'inline-flex max-w-48 items-center gap-1 overflow-hidden rounded-md',
        'bg-info-bg px-1.5 py-0.5 text-xs leading-xs text-info',
        'border border-info-border/70',
        className
      )}
      {...props}
    >
      {icon ? (
        <span className="inline-flex size-3.5 shrink-0 items-center justify-center text-current [&_svg]:size-3.5">
          {icon}
        </span>
      ) : null}
      <span className="min-w-0 truncate">{label}</span>
      {onRemove ? (
        <button
          type="button"
          aria-label={removeLabel}
          className={cn(
            'ml-0.5 inline-flex size-4 shrink-0 items-center justify-center rounded-sm text-info/70 transition-colors',
            'hover:bg-info/10 hover:text-info',
            'focus:outline-none focus-visible:ring-2 focus-visible:ring-primary-border'
          )}
          onClick={(event) => {
            event.stopPropagation()
            onRemove()
          }}
        >
          <CloseLine className="size-3" />
        </button>
      ) : null}
    </span>
  )
)

ChatContextTag.displayName = 'ChatContextTag'
