import { Children, ReactNode } from 'react'
import { headingVariants } from './variants'

import type { VariantProps } from 'class-variance-authority'

type HeadingLevel = 'h1' | 'h2' | 'h3' | 'h4' | 'h5'

export interface HeadingProps
  extends Omit<React.HTMLAttributes<HTMLHeadingElement>, 'color'>,
    VariantProps<typeof headingVariants> {
  as?: HeadingLevel
  level?: HeadingLevel
}

/**
 * @deprecated Use `Typography` instead.
 */
export default function Title({
  /**
   * What styling to use, based on heading level. If not provided `level`
   * will determine the styling.
   */
  as,
  children,
  className = '',
  color,
  /**
   * What HTML tag to use. Defaults to h1.
   */
  level = 'h1',
  textAlign,
  textTransform,
  ...rest
}: HeadingProps) {
  if (checkForEmptyChildren(children) === 0) {
    return null
  }
  const Hx = level
  const classNames = headingVariants({
    className,
    color,
    textAlign,
    textTransform,
    type: as ?? level,
  })
  return (
    <Hx {...rest} className={classNames}>
      {children}
    </Hx>
  )
}

function checkForEmptyChildren(children: ReactNode) {
  return Children.toArray(children).filter((child) => {
    if (child === '') {
      return false
    } else if (child == null) {
      return false
    } else {
      return true
    }
  }).length
}
