import classNames from "classnames"
import PropTypes from "prop-types"
import React from "react"

const SIZES = {
  xs: { className: "text-xs leading-4" },
  sm: { className: "text-sm leading-6" },
  md: { className: "text-base leading-5" },
  lg: { className: "text-lg leading-8" },
  xl: { className: "text-2xl leading-8" },
  "2xl": { className: "leading-10", style: { fontSize: "2rem" } },
}

const hasCSSUnit = (size) => size.match(/px|r?em|%$/)

const getSize = (size) => {
  if (hasCSSUnit(size)) return { style: { fontSize: size } }
  return SIZES[size]
}

export default function Text({
  as: Component = "div",
  className,
  children,
  size = "md",
  weight,
  color,
  ...props
}) {
  className = classNames(className, getSize(size).className, {
    [`font-${weight}`]: weight,
    [`text-${color}`]: color,
  })

  const style = SIZES[size].style || {}

  return (
    <Component className={className} style={style} {...props}>
      {children}
    </Component>
  )
}

Text.propTypes = {
  /** An HTML tag in which the text will be rendered. */
  as: PropTypes.string,
  className: PropTypes.string,
  children: PropTypes.node,
  size: PropTypes.oneOf(Object.keys(SIZES)),
  weight: PropTypes.oneOf(["light", "normal", "semibold"]),
  /** A Tailwind-style text color such as `red-400`. */
  color: PropTypes.string,
}
