import { h, type FunctionComponent, type PointerEventHandler } from 'preact'
import cn from 'classnames'

export default function buttonFactory({ defaults, icons, styles }) {
  const Button: FunctionComponent<{
    autoHeight?: boolean
    className?: string
    color?: string
    design?: string
    disabled?: boolean
    fullWidth?: boolean
    icon?: string
    iconSize?: string
    invert?: boolean
    onClick?: PointerEventHandler<HTMLButtonElement>
    size?: string
    tabIndex?: number
    tag?: string
    title?: string
    type?: 'button' | 'reset' | 'submit'
  }> = ({
    autoHeight = defaults?.autoHeight,
    children,
    className,
    color = defaults?.color,
    design = defaults?.design,
    disabled,
    fullWidth = defaults?.fullWidth,
    icon = defaults?.icon,
    iconSize,
    invert = defaults?.invert,
    onClick,
    size = defaults?.size,
    tabIndex,
    title,
    type,
  }) => (
    <button
      className={cn(
        styles.base,
        design && styles[design],
        size && styles[size],
        color && styles[color],
        autoHeight && styles.autoHeight,
        fullWidth && styles.fullWidth,
        invert && styles.invert,
        className,
      )}
      style={iconSize && { '--icon-size': iconSize }}
      disabled={disabled}
      onClick={onClick}
      tabIndex={tabIndex}
      title={title}
      type={type}
    >
      {icon && <i className={styles.icon} style={{ maskImage: `url(${icons[icon] || icon})` }} />}
      {children && <span>{children}</span>}
    </button>
  )

  return Button
}
