import { Button as ButtonRAC } from "react-aria-components"
import { Loading } from "../Loading/Loading"

import { MaterialIcon } from "../Icons/MaterialIcon"
import { Typography } from "../Typography"
import type { ButtonProps } from "./types"
import { variants } from "./variants"

export function Button({
  variant,
  color,
  size,
  wrapping,
  fullWidth,
  leadingIconName,
  trailingIconName,
  className,
  children,
  ...props
}: ButtonProps) {
  const classNames = variants({
    variant,
    color,
    size,
    wrapping,
    fullWidth,
    className,
  })

  return (
    <Typography
      variant={
        size === "sm"
          ? "Body/Supporting text (caption)/smBold"
          : "Body/Paragraph/mdBold"
      }
    >
      <ButtonRAC {...props} className={classNames}>
        {({ isPending }) => {
          return (
            <>
              {leadingIconName && !isPending ? (
                <MaterialIcon
                  icon={leadingIconName}
                  color="CurrentColor"
                  size={size === "sm" ? 20 : 24}
                />
              ) : null}
              {children}
              {trailingIconName && !isPending ? (
                <MaterialIcon
                  icon={trailingIconName}
                  color="CurrentColor"
                  size={size === "sm" ? 20 : 24}
                />
              ) : null}
              {isPending ? (
                <Loading size={size === "sm" ? 18 : 20} type="CurrentColor" />
              ) : null}
            </>
          )
        }}
      </ButtonRAC>
    </Typography>
  )
}
