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

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

import { InputType } from 'src/types/forms';
import { useLokaliseTranslation } from 'src/utils/i18n';

const dismissedOptionalQuestions = [InputType.INFO, InputType.AUTOCOMPLETE];

type Props = {
  name: string;
  title: string;
  required: boolean;
  inputType: InputType;
};

const QuestionTitle = ({ name, title, required, inputType }: Props) => {
  const { t } = useLokaliseTranslation('validations');

  const { fieldState } = useController({ name });
  const hasError = !!Object.values(fieldState.error ?? {}).length;
  const showOptionalLabel =
    !required && !dismissedOptionalQuestions.includes(inputType);

  const getSuffix = () => {
    if (required) return '*';
    if (showOptionalLabel) return ` (${t('optional')})`;
    return '';
  };

  return (
    <Typography
      variant="globalS"
      fontWeight="fontWeightSemiBold"
      sx={{
        color: ({ palette }) =>
          hasError
            ? palette.new.text.feedback.error
            : palette.new.text.neutral.default,
      }}
    >
      {title}
      {getSuffix()}
    </Typography>
  );
};

export default QuestionTitle;
