import clsx from 'clsx';
import React from 'react';

import SvgIcon from './svg-icon';
import Text from './text';

interface IIconButton extends React.ButtonHTMLAttributes<HTMLButtonElement> {
  /** Class name for the <svg> icon. */
  iconClassName?: string;
  /** URL to the svg icon. */
  src: string;
  /** Text to display next to the button. */
  text?: string;
  /** Predefined styles to display for the button. */
  theme?: 'seamless' | 'outlined' | 'secondary' | 'transparent' | 'dark';
  /** Override the data-testid */
  'data-testid'?: string;
  /** URL address */
  href?: string;
}

/** A clickable icon. */
const IconButton = React.forwardRef(
  (props: IIconButton, ref: React.ForwardedRef<HTMLButtonElement>): React.JSX.Element => {
    const { src, className, iconClassName, text, theme = 'seamless', ...filteredProps } = props;

    const Component = (props.href ? 'a' : 'button') as 'button';

    return (
      <Component
        ref={ref}
        type='button'
        className={clsx(
          '⁂-icon-button flex items-center space-x-2 rounded-full p-1 focus:outline-none focus:ring-2 focus:ring-primary-500 focus:ring-offset-2 dark:ring-offset-0',
          {
            'bg-white dark:bg-transparent': theme === 'seamless',
            'border border-solid border-gray-400 bg-transparent text-gray-900 hover:border-primary-300 focus:border-primary-500 focus:ring-primary-500 dark:border-gray-800 dark:text-gray-100 dark:hover:border-primary-700':
              theme === 'outlined',
            'border-transparent bg-primary-100 text-primary-500 hover:bg-primary-50 focus:bg-primary-100 dark:bg-primary-800 dark:text-primary-200 dark:hover:bg-primary-700 dark:focus:bg-primary-800':
              theme === 'secondary',
            'bg-gray-900 text-white': theme === 'dark',
            'opacity-50': filteredProps.disabled,
          },
          className,
        )}
        {...filteredProps}
        data-testid={filteredProps['data-testid'] ?? 'icon-button'}
        {...(props.href ? ({ target: '_blank' } as any) : {})}
      >
        <SvgIcon src={src} className={iconClassName} aria-hidden />

        {text ? (
          <Text tag='span' theme='inherit' size='sm'>
            {text}
          </Text>
        ) : null}
      </Component>
    );
  },
);

export { IconButton as default };
