import type { HTMLAttributes, ReactNode } from 'react'
import { cv, type VariantProps } from '../../lib/cv.js'

const badge = cv('inline-flex items-center rounded-full px-2.5 py-0.5 text-xs font-medium', {
  variants: {
    tone: {
      neutral: 'bg-muted text-muted-foreground',
      success: 'bg-success/10 text-success',
      warning: 'bg-warning/10 text-warning',
      danger: 'bg-destructive/10 text-destructive',
      info: 'bg-info/10 text-info',
      primary: 'bg-[var(--primary)]/15 text-[var(--primary)] dark:bg-[var(--primary)]/25',
    },
    size: {
      sm: 'px-2 py-0.5 text-[10px]',
      md: 'px-2.5 py-0.5 text-xs',
      lg: 'px-3 py-1 text-sm',
    },
  },
  defaultVariants: { tone: 'neutral', size: 'md' },
})

export type BadgeVariants = VariantProps<typeof badge>

/**
 * Map document statuses to badge tones. Exposed so callers can reuse the
 * mapping (e.g. for the same status rendered as a dot indicator).
 */
export const STATUS_TONE: Record<DocumentStatus, BadgeVariants['tone']> = {
  published: 'success',
  draft: 'neutral',
  archived: 'warning',
  scheduled: 'info',
}

export const STATUS_LABEL: Record<DocumentStatus, string> = {
  published: 'Published',
  draft: 'Draft',
  archived: 'Archived',
  scheduled: 'Scheduled',
}

export type DocumentStatus = 'published' | 'draft' | 'archived' | 'scheduled'

export interface BadgeProps extends HTMLAttributes<HTMLSpanElement>, BadgeVariants {
  /**
   * Shorthand for the canonical document status badge. When set, takes
   * precedence over `tone` and uses the matching label.
   */
  status?: DocumentStatus
  /** Render as outlined (border + transparent background). */
  outline?: boolean
  children?: ReactNode
}

const OUTLINE_CLASS = 'border border-current bg-transparent'

/**
 * Generic typed badge. Pass `status` for the canonical document-status
 * variants (preserves the original Badge API), or `tone` / `outline` /
 * `size` for everything else.
 */
export function Badge({ status, tone, outline, size, className, children, ...rest }: BadgeProps) {
  const extras = [outline ? OUTLINE_CLASS : '', className].filter(Boolean).join(' ')
  if (status) {
    return (
      <span className={badge({ tone: STATUS_TONE[status], size, class: extras })} {...rest}>
        {children ?? STATUS_LABEL[status]}
      </span>
    )
  }
  return (
    <span className={badge({ tone, size, class: extras })} {...rest}>
      {children}
    </span>
  )
}

export { badge as badgeVariants }
