import React, { ReactNode } from 'react';
import AntButton from '@ant-design/react-native/lib/button';
import type { ButtonProps } from './type';
import { ButtonTheme } from './theme';
import { Text } from '../Typography/text';
import { getButtonType, getTextStyle } from './utils';

const renderChildren = (children: ReactNode, textStyle: any): ReactNode => {
  if (typeof children === 'string') {
    return <Text style={textStyle}>{children}</Text>;
  } else if (Array.isArray(children)) {
    return (
      <>
        {children.map((child, index) =>
          typeof child === 'string' ? (
            <Text style={textStyle} key={index}>
              {child}
            </Text>
          ) : (
            child
          )
        )}
      </>
    );
  } else {
    return children;
  }
};

export const Button: React.FC<ButtonProps> = ({
  style,
  theme = 'primary',
  block = false,
  testID = 'default',
  outline = false,
  children,
  ...props
}) => {
  const textStyle = getTextStyle(theme);
  const buttonType = getButtonType(theme);
  const blockStyle = block ? ButtonTheme.block : null;
  const outlineStyle = outline ? ButtonTheme.outline : null;

  return (
    <AntButton
      type={buttonType}
      style={[ButtonTheme[theme], blockStyle, outlineStyle, style]}
      testID={`hcds-mobile-btn-${testID}`}
      accessibilityLabel={`hcds-mobile-btn-${testID}`}
      {...props}
    >
      {renderChildren(children, textStyle)}
    </AntButton>
  );
};
