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

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

import { OptionsCard } from 'src/pages/newCommunity/components/OptionsCard';
import { useLokaliseTranslation } from 'src/utils/i18n';
import { getLanguageOptions } from 'src/utils/languages';

export const LanguageInput = () => {
  const { t } = useLokaliseTranslation('authentication');

  const {
    control,
    watch,
    formState: { errors },
  } = useFormContext();
  const companyLanguage = watch('language');

  return (
    <>
      <Controller
        control={control}
        name="language"
        rules={{ required: true }}
        render={({ field: { onChange } }) => (
          <Box
            sx={{
              display: 'flex',
              justifyContent: 'space-between',
              alignItems: 'center',
              flexDirection: 'column',
            }}
          >
            {getLanguageOptions().map(language => (
              <OptionsCard
                key={language.value}
                onClick={() => onChange(language.value)}
                className={companyLanguage === language.value ? 'active' : ''}
              >
                <Box
                  sx={{
                    display: 'flex',
                    alignItems: 'center',
                  }}
                >
                  <ListItemText
                    primary={
                      <Typography
                        color="textPrimary"
                        variant="subtitle2"
                        sx={{ textTransform: 'uppercase' }}
                      >
                        {language.value}
                      </Typography>
                    }
                  />
                  <Typography sx={{ mx: 1 }}>{'|'}</Typography>
                  <Typography>{t(language.label)}</Typography>
                </Box>
              </OptionsCard>
            ))}
          </Box>
        )}
      />
      {errors?.language && (
        <Typography sx={{ color: 'red', mt: 1, ml: 1 }}>
          {t('MANDATORY_FIELD')}
        </Typography>
      )}
    </>
  );
};

export default LanguageInput;
