import { forwardRef } from 'react';

import { Rating as MuiRating, Stack, useTheme } from '@mui/material';
import { IconStar, IconStarFilled } from '@tabler/icons-react';

import CustomHelperText from '../Inputs/Base/CustomHelperText';

import { type RatingProps } from './types';
import { getNumericValue, getValidMax, getValidSize } from './utils';

const Rating = forwardRef<HTMLDivElement, RatingProps>(
  ({ max, size, value, error, helperText, ...props }, ref) => {
    const theme = useTheme();
    const newPalette = theme.palette?.new;
    const validMax = getValidMax(max);
    const validSize = getValidSize(size);
    const numericValue = getNumericValue(value);

    return (
      <Stack>
        <MuiRating
          ref={ref}
          sx={{
            color: newPalette?.action.button.background.primary.default,
            gap: 0.5,
          }}
          emptyIcon={
            <IconStar
              size={validSize}
              color={newPalette?.action.button.background.primary.disabled}
            />
          }
          icon={<IconStarFilled size={validSize} />}
          max={validMax}
          value={numericValue || 0}
          {...props}
          precision={1}
        />
        <CustomHelperText
          error={error}
          helperText={helperText}
          value={value?.toString() || ''}
        />
      </Stack>
    );
  },
);

export type { RatingProps };

Rating.displayName = 'Rating';

export default Rating;
