import { IconContainerProps } from '@material-hu/mui/Rating';
import Stack from '@material-hu/mui/Stack';
import Typography from '@material-hu/mui/Typography';

import Button, {
  ButtonProps,
} from '@material-hu/components/design-system/Buttons/Button';

import {
  FormRatingProps,
  FormRating,
} from 'src/components/FormInputs/FormRating';

const getLabelText = (value: number) => `${value}`;

type NumberButtonProps = ButtonProps & {
  iconContainerProps: IconContainerProps;
  max: number;
};

const NumberButton = ({
  iconContainerProps,
  max,
  ...buttonProps
}: NumberButtonProps) => {
  const { value } = iconContainerProps;

  return (
    <Button
      variant="outlined"
      color="primary"
      sx={{
        minWidth: '40px',
        width: '100%',
        ...(value < max && {
          borderRightColor: 'transparent',
          borderTopRightRadius: 0,
          borderBottomRightRadius: 0,
        }),
        ...(value > 1 && {
          ml: '-1px',
          borderTopLeftRadius: 0,
          borderBottomLeftRadius: 0,
        }),
      }}
      {...buttonProps}
    >
      {value}
    </Button>
  );
};

export type FormNumberRatingProps = FormRatingProps & {
  numberButtonProps?: ButtonProps;
  lowHelperText?: string;
  highHelperText?: string;
  fullWidth?: boolean;
};

export const FormNumberRating = ({
  numberButtonProps,
  lowHelperText,
  highHelperText,
  max = 5,
  fullWidth = false,
  ...ratingProps
}: FormNumberRatingProps) => {
  return (
    <Stack
      sx={{
        flexDirection: 'column',
        gap: '2px',
        width: fullWidth ? '100%' : undefined,
      }}
    >
      <FormRating
        {...ratingProps}
        getLabelText={getLabelText}
        highlightSelectedOnly
        max={max}
        IconContainerComponent={iconContainerProps => (
          <NumberButton
            {...numberButtonProps}
            iconContainerProps={iconContainerProps}
            max={max}
          />
        )}
        sx={{
          display: 'inline-flex',
          width: '100%',
          borderRadius: 0.5,
          '& > span': {
            flex: 1,
          },
        }}
      />
      {(lowHelperText || highHelperText) && (
        <Stack
          sx={{
            gap: 1,
            flexDirection: 'row',
            justifyContent: 'space-between',
            alignItems: 'center',
          }}
        >
          {lowHelperText && (
            <Typography
              variant="caption"
              sx={{
                color: '#11192761',
              }}
            >
              {lowHelperText}
            </Typography>
          )}
          {highHelperText && (
            <Typography
              variant="caption"
              sx={{
                color: '#11192761',
              }}
            >
              {highHelperText}
            </Typography>
          )}
        </Stack>
      )}
    </Stack>
  );
};

export default FormNumberRating;
