import { ReactNode } from 'react'
import { Info, CheckCircle, AlertTriangle, XCircle, X } from 'lucide-react'
import styles from './Alert.module.css'

type AlertVariant = 'info' | 'success' | 'warning' | 'error'

interface AlertProps {
  variant?: AlertVariant
  title?: string
  children?: ReactNode
  dismissible?: boolean
  onDismiss?: () => void
  icon?: ReactNode
  className?: string
}

const DEFAULT_ICONS: Record<AlertVariant, ReactNode> = {
  info: <Info size={16} />,
  success: <CheckCircle size={16} />,
  warning: <AlertTriangle size={16} />,
  error: <XCircle size={16} />,
}

const ARIA_ROLES: Record<AlertVariant, 'alert' | 'status'> = {
  error: 'alert',
  warning: 'alert',
  info: 'status',
  success: 'status',
}

export function Alert({
  variant = 'info',
  title,
  children,
  dismissible = false,
  onDismiss,
  icon,
  className,
}: AlertProps) {
  const resolvedIcon = icon !== undefined ? icon : DEFAULT_ICONS[variant]
  const role = ARIA_ROLES[variant]

  const classes = [styles.alert, styles[variant], className ?? '']
    .filter(Boolean)
    .join(' ')

  return (
    <div className={classes} role={role}>
      <span className={styles.icon} aria-hidden="true">
        {resolvedIcon}
      </span>

      <div className={styles.content}>
        {title && <div className={styles.title}>{title}</div>}
        {children && <div className={styles.body}>{children}</div>}
      </div>

      {dismissible && (
        <button
          className={styles.dismissBtn}
          onClick={onDismiss}
          aria-label="Dismiss alert"
          type="button"
        >
          <X size={14} />
        </button>
      )}
    </div>
  )
}
