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

import InfoOutlinedIcon from '@material-hu/icons/material/InfoOutlined';
import Box from '@material-hu/mui/Box';
import TextField from '@material-hu/mui/TextField';
import Tooltip from '@material-hu/mui/Tooltip';
import Typography from '@material-hu/mui/Typography';

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

export const FormNameOrganization: FC = () => {
  const { t } = useLokaliseTranslation('authentication');

  const {
    control,
    formState: { errors },
  } = useFormContext();

  return (
    <>
      <Controller
        control={control}
        name="companyName"
        rules={{
          required: true,
          pattern: {
            value: INSTANCE_NAME_REGEX,
            message: t('INVALID_PATTERN_FIELD'),
          },
        }}
        render={({ field }) => (
          <TextField
            id="companyName"
            variant="outlined"
            error={!!errors?.companyName}
            sx={{ m: 0 }}
            placeholder={t('NAME_ORGANIZATION_PLACEHOLDER')}
            fullWidth
            margin="normal"
            {...field}
          />
        )}
      />
      {errors?.companyName && (
        <>
          {errors?.companyName?.type === 'required' ? (
            <Typography sx={{ color: 'red', mt: 1, ml: 1 }}>
              {t('MANDATORY_FIELD')}
            </Typography>
          ) : (
            <Box sx={{ display: 'flex', alignItems: 'center' }}>
              <Typography sx={{ color: 'red', mt: 1, ml: 1 }}>
                {errors?.companyName.message as string}
              </Typography>
              <Tooltip
                title={t('INSTANCE_VALID_CHARACTERS')}
                placement="top"
              >
                <InfoOutlinedIcon sx={{ mt: 1, ml: 1, fontSize: '20px' }} />
              </Tooltip>
            </Box>
          )}
        </>
      )}
    </>
  );
};

export default FormNameOrganization;
