import { Button as MuiButton } from '@mui/material';
import { styled } from '@mui/material/styles';
import { Button as RaButton, ButtonProps as RaButtonProps, useTranslate } from 'react-admin';
import { Path } from 'react-router';

type ButtonProps = RaButtonProps & {
  /**
   * Disable icon only in small screens.
   */
  disableIconOnly?: boolean;
};

const PREFIX = 'RaButton';
function getLinkParams(locationDescriptor?: LocationDescriptor | string) {
  // eslint-disable-next-line eqeqeq
  if (locationDescriptor == undefined) {
    return undefined;
  }

  if (typeof locationDescriptor === 'string') {
    return { to: locationDescriptor };
  }

  const { redirect, replace, state, ...to } = locationDescriptor;
  return {
    to,
    redirect,
    replace,
    state
  };
}
const StyledButton = styled(MuiButton, {
  name: PREFIX,
  overridesResolver: (_props, styles) => styles.root
})({
  '&.MuiButton-sizeSmall': {
    // fix for icon misalignment on small buttons, see https://github.com/mui/material-ui/pull/30240
    lineHeight: 1.5
  }
});

/**
 * A button that can be displayed as a floating button on small screens.
 * @param props The component props.
 * @returns The component.
 */
function Button(props: ButtonProps): JSX.Element {
  const {
    disableIconOnly = false,
    label,
    children,
    className,
    color,
    size,
    disabled,
    alignIcon,
    to: locationDescriptor,
    ...rest
  } = props;
  const translate = useTranslate();
  const linkParams = getLinkParams(locationDescriptor);

  if (disableIconOnly) {
    const translatedLabel = label ? translate(label, { _: label }) : undefined;
    return (
      <StyledButton
        className={className}
        color={color}
        size={size}
        aria-label={translatedLabel}
        disabled={disabled}
        startIcon={alignIcon === 'left' && children ? children : undefined}
        endIcon={alignIcon === 'right' && children ? children : undefined}
        {...linkParams}
        {...rest}
      >
        {translatedLabel}
      </StyledButton>
    );
  }
  return <RaButton {...props} />;
}

type LocationDescriptor = Partial<Path> & {
  redirect?: boolean;
  state?: any;
  replace?: boolean;
};

export { Button };
export type { ButtonProps, LocationDescriptor };
