import React from 'react';
import { clsx } from 'clsx';
import { RecipeVariants } from '@vanilla-extract/recipes';

import { forwardRef } from '../utils/react';
import { Box } from '../box';
import * as css from './button.css';

/*-- Types --*/

export type ButtonVariantProps = NonNullable<RecipeVariants<typeof css.button>>;

export interface ButtonProps extends Omit<ButtonVariantProps, 'hasIcon'> {
  startIcon?: React.ReactNode;
  endIcon?: React.ReactNode;
}

/*-- Main --*/

export const Button = forwardRef<'button', ButtonProps>(function Button(
  {
    as = 'button',
    children,
    className,
    startIcon,
    endIcon,
    variant = 'filled',
    color = 'primary',
    fontSize = 'base',
    width = 'sm',
    subtle,
    ...rest
  },
  ref,
) {
  const hasIcon = Boolean(startIcon || endIcon);

  const cn = clsx(
    className,
    css.button({
      variant,
      color,
      subtle,
      fontSize,
      width,
      hasIcon,
    }),
  );

  return (
    <Box ref={ref} as={as} className={cn} {...rest}>
      {startIcon}
      {hasIcon ? <span>{children}</span> : children}
      {endIcon}
    </Box>
  );
});
