import { useController, useFormContext } from 'react-hook-form';

import Stack from '@material-hu/mui/Stack';

import { appearFromBottom } from '@material-hu/utils/animations';
import Title from '@material-hu/components/design-system/Title';
import ButtonGroup from '@material-hu/components/design-system/ButtonGroup';
import { type Value } from '@material-hu/components/design-system/ButtonGroup/types';

import useRestrictedTranslation from 'src/hooks/useRestrictedTranslation';
import { type NpsSurveyForm, type NpsSurveyFormProp } from './types';

type SatisfactionRatingProps = {
  ratingProp: NpsSurveyFormProp;
  question: string;
};

const NpsSurveyRating = ({ ratingProp, question }: SatisfactionRatingProps) => {
  const { t } = useRestrictedTranslation('backoffice_only');

  const { control } = useFormContext<NpsSurveyForm>();
  const { field } = useController({ name: ratingProp, control });
  const normalizedCurrentRating = Number(field.value) - 1;

  const handleOptionSelection = (rating: Value) => {
    if (rating !== null) field.onChange(rating + 1);
  };

  const labels = Array.from({ length: 5 }, (_, index) =>
    t(`nps_survey_flow_dialog.rating_satisfaction_${index + 1}`),
  );

  return (
    <Stack sx={{ gap: 2, animation: `${appearFromBottom} 0.3s ease-in-out` }}>
      <Title
        title={question}
        variant="S"
      />

      <ButtonGroup
        fullWidth
        labels={labels}
        value={normalizedCurrentRating}
        showCheckIcon={false}
        onChange={handleOptionSelection}
        slotProps={{
          button: { sx: { height: 72 } },
        }}
      />
    </Stack>
  );
};

export default NpsSurveyRating;
