import { useFormContext } from 'react-hook-form';
import { type TFunction, Trans } from 'react-i18next';

import Stack from '@material-hu/mui/Stack';
import Typography from '@material-hu/mui/Typography';
import { fadeIn } from '@material-hu/utils/animations';

import CardContainer from '@material-hu/components/design-system/CardContainer';
import FormInputClassic from '@material-hu/components/design-system/Inputs/Classic/form';

import { useLokaliseTranslation } from 'src/utils/i18n';

import { MAX_ANONYMITY_THRESHOLD, MIN_ANONYMITY_THRESHOLD } from '../constants';

type AnonymityThresholdFormProps = {
  resultsName: string;
  commentName: string;
};

const AnonymityThresholdForm = ({
  resultsName,
  commentName,
}: AnonymityThresholdFormProps) => {
  const {
    trigger,
    formState: { touchedFields, errors },
  } = useFormContext();
  const { t } = useLokaliseTranslation('people_experience');

  const fields = [
    {
      name: resultsName,
      label: t('anonymity.for_results'),
    },
    {
      name: commentName,
      label: t('anonymity.for_comments'),
    },
  ];

  return (
    <CardContainer
      color="grey"
      sx={{
        animation: `${fadeIn} 250ms ease-in-out backwards`,
      }}
      fullWidth
    >
      <Stack sx={{ gap: 2 }}>
        <Typography
          variant="globalS"
          color="text.secondary"
        >
          <Trans
            t={t as TFunction}
            i18nKey="anonymity.config_threshold_description"
            ns="people_experience"
            components={{
              strong: <strong />,
            }}
          />
        </Typography>
        <Stack sx={{ gap: 2, flexDirection: 'row' }}>
          {fields.map(({ name, label }) => (
            <FormInputClassic
              key={name}
              name={name}
              inputProps={{
                label,
                hasCounter: false,
                showClear: false,
                helperText: t('anonymity.config_threshold_helper', {
                  min: MIN_ANONYMITY_THRESHOLD,
                  max: MAX_ANONYMITY_THRESHOLD,
                }),
                onBlur: () => {
                  trigger(name);
                },
                success: !errors[name] && touchedFields[name],
                transform: {
                  input: value => value.replace(/\D/g, ''),
                },
              }}
            />
          ))}
        </Stack>
      </Stack>
    </CardContainer>
  );
};

export default AnonymityThresholdForm;
