import React, { useMemo } from 'react';

import ToggleButton, { ToggleButtonProps } from '@mui/material/ToggleButton';

import { Typography, TYPOGRAPHY_TYPE } from 'components/Typography';
import { bem } from 'utils/bem';
import { truncateText } from 'utils/text';

import { THEME } from '../../constants';
import { TextOnlySingleToggleProps, SINGLE_TOGGLE_TYPE } from './types';
import { MAX_CHARACHTERS_VISIBLE } from './constants';

import styles from './single-toggle.scss';

export const singleToggleClassName = bem(styles, 'single-toggle');

export const SingleToggle = React.forwardRef(
  <T extends number | string>(
    props: TextOnlySingleToggleProps<T>,
    forwardedRef: React.ForwardedRef<HTMLButtonElement>,
  ) => {
    const { theme = THEME.light, className, toggleType, dataAttributes, ...otherProps } = props;

    const content = useMemo(() => {
      switch (toggleType) {
        case SINGLE_TOGGLE_TYPE.textOnly:
          const { text } = props;

          return (
            <Typography
              type={TYPOGRAPHY_TYPE.subtitle3}
              className={singleToggleClassName('text')}
            >
              {truncateText(text, MAX_CHARACHTERS_VISIBLE)}
            </Typography>
          );
      }
    }, [toggleType, props]);

    return (
      <ToggleButton
        {...dataAttributes}
        ref={forwardedRef}
        disableRipple
        className={singleToggleClassName(null, { [theme]: true }, className)}
        {...(otherProps as ToggleButtonProps)}
      >
        {content}
      </ToggleButton>
    );
  },
);

SingleToggle.displayName = 'SingleToggle';
