import * as Ariakit from '@ariakit/react';
import { getClassNames } from '@websolutespa/bom-core';
import React, { forwardRef } from 'react';
import styled, { css } from 'styled-components';
import { SizeVariant, getVariant, useVariants } from '../../variants';
import { UIComponentWithRef, UIStyledComponentProps } from '../types';
import { getCssResponsive } from '../utils';
import { CssDefault, IButtonVariants, buttonVariants } from './button.variants';

const StyledButton = styled.div<ButtonProps>`
  ${CssDefault}
  ${props => getVariant(props.variant, props.variants)}
  ${props => (css`font-size: var(--button-size-${props.size || 'md'});`)}
  ${props => getCssResponsive(props)}
`;

type Props = Ariakit.ButtonProps & {
  children?: React.ReactNode;
  size?: SizeVariant;
  variant?: keyof typeof buttonVariants | (string & {});
  variants?: IButtonVariants;
};

export type ButtonProps = UIStyledComponentProps<Props>;

export type ButtonComponent<C extends React.ElementType = 'button'> = UIComponentWithRef<C, Props>;

export const Button: ButtonComponent = forwardRef(
  function Button({
    children,
    className,
    as = 'button',
    variants,
    accessibleWhenDisabled,
    autoFocus,
    clickOnEnter,
    clickOnSpace,
    ...props
  }, ref) {
    const classNames = getClassNames('button', className, { disabled: props.disabled }, props.variant);
    const globalVariants = useVariants('button', buttonVariants);
    variants = variants || globalVariants;
    return (
      <Ariakit.Button
        accessibleWhenDisabled={accessibleWhenDisabled}
        autoFocus={autoFocus}
        clickOnEnter={clickOnEnter}
        clickOnSpace={clickOnSpace}
        render={
          <StyledButton className={classNames} ref={ref} as={as} variants={variants} {...props}>{children}</StyledButton>
        } />
    );
  });
