import { FC } from 'react';

import Box from '@material-hu/mui/Box';
import CircularProgress from '@material-hu/mui/CircularProgress';
import { LoadingButtonProps as LoadingButtonUiProps } from '@material-hu/mui/lab';

import Button from '@material-hu/components/design-system/Buttons/Button';

export type LoadingButtonProps = LoadingButtonUiProps;

export const LoadingButton: FC<
  React.PropsWithChildren<LoadingButtonProps>
> = props => {
  const {
    loading = false,
    loadingIndicator = (
      <CircularProgress
        size={16}
        color="inherit"
      />
    ),
    loadingPosition = 'center',
    children,
    ...buttonProps
  } = props;

  const renderLoading = () => {
    switch (loadingPosition) {
      case 'start':
        return (
          <>
            {loadingIndicator}
            <Box sx={{ mr: 1 }} />
            {children}
          </>
        );
      case 'end':
        return (
          <>
            {children}
            <Box sx={{ mr: 1 }} />
            {loadingIndicator}
          </>
        );
      case 'center':
        return <>{loadingIndicator}</>;
      default:
        return <>{loadingIndicator}</>;
    }
  };

  return (
    <Button {...buttonProps}>{loading ? renderLoading() : children}</Button>
  );
};

export default LoadingButton;
