All files / src/components/Recipe/Rating RecipeRating.tsx

0% Statements 0/13
0% Branches 0/11
0% Functions 0/2
0% Lines 0/12

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72                                                                                                                                               
'use client';
 
import { useMutation } from '@apollo/client/react';
import { Group, Rating, Stack, Text } from '@mantine/core';
import { notifications } from '@mantine/notifications';
import { useTranslations } from 'next-intl';
import { RATE_RECIPE } from '@/lib/graphql/mutations';
import type { RecipeRatingProps } from './types';
 
const RecipeRating = ({
  recipeId,
  userRating,
  averageRating,
  ratingsCount,
  readOnly = false,
}: RecipeRatingProps) => {
  const translate = useTranslations('recipe');
  const [rateRecipe, { loading }] = useMutation(RATE_RECIPE);
 
  const handleRatingChange = async (value: number) => {
    if (readOnly || loading) return;
 
    try {
      await rateRecipe({
        variables: {
          ratingInput: {
            recipeId,
            ratingValue: value,
          },
        },
        // Optimistic UI could be added here, but for now let's keep it simple
        refetchQueries: ['getRecipeById'],
      });
      notifications.show({
        title: translate('ratingSuccess'),
        message: translate('ratingSuccessMessage'),
        color: 'green',
      });
    } catch (error) {
      console.error('Rating failed:', error);
      notifications.show({
        title: translate('ratingError'),
        message: translate('ratingErrorMessage'),
        color: 'red',
      });
    }
  };
 
  return (
    <Stack gap="xs">
      <Group gap="sm">
        <Rating
          value={userRating || averageRating}
          onChange={handleRatingChange}
          readOnly={readOnly || loading}
          fractions={2}
        />
        <Text size="sm" c="dimmed">
          ({ratingsCount} {translate('ratingsCount')})
        </Text>
      </Group>
      {userRating && (
        <Text size="xs" c="dimmed" style={{ fontStyle: 'italic' }}>
          {translate('yourRating')}: {userRating}
        </Text>
      )}
    </Stack>
  );
};
 
export default RecipeRating;