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

import AddCircleOutlineIcon from '@material-hu/icons/material/AddCircleOutline';
import DeleteIcon from '@material-hu/icons/material/Delete';
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 Button from '@material-hu/components/design-system/Buttons/Button';

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

import { InvitationFormData } from '../NewPeopleDialog';

export const InvitationForm = () => {
  const { t } = useLokaliseTranslation('invitePeople');

  const {
    control,
    formState: { errors },
    watch,
  } = useFormContext<InvitationFormData>();

  const { fields, append, remove } = useFieldArray({
    control,
    name: 'sendInvitations',
  });

  const baseEmailRules = useRules({
    requiredWithMessage: true,
    email: true,
  });

  const buildEmailRules = (index: number) => {
    const notDuplicate = (value: string) => {
      const emails = (watch('sendInvitations') ?? []).map(e => e?.email || '');
      const duplicates = emails.filter((e, i) => i !== index && e === value);
      return duplicates.length === 0 || t('REPEAT_EMAIL_ERROR');
    };
    return {
      ...baseEmailRules,
      validate: {
        ...(baseEmailRules.validate ?? {}),
        notEqualEmail: notDuplicate,
      },
    };
  };

  return (
    <>
      {fields.map((item, index) => (
        <Box
          key={item.id}
          sx={{ mb: 2 }}
        >
          <Box
            key={item.id}
            sx={{
              display: 'flex',
              alignItems: 'center',
              '& .css-3qmeec-MuiInputBase-input-MuiOutlinedInput-input': {
                height: '0.6em',
              },
            }}
          >
            <Controller
              control={control}
              name={`sendInvitations.${index}.email`}
              rules={buildEmailRules(index)}
              render={({ field }) => (
                <TextField
                  id={`sendInvitations.${index}.email`}
                  variant="outlined"
                  error={!!errors?.sendInvitations?.[index]?.email}
                  sx={{ width: { xs: '100%', sm: '92%' }, m: 0 }}
                  placeholder={t('INVITE_PEOPLE_PLACEHOLDER')}
                  fullWidth
                  margin="normal"
                  {...field}
                />
              )}
            />
            <Tooltip
              title={t('REMOVE_FIELD')}
              placement="top"
            >
              <Button
                sx={{ ml: { xs: 0, sm: 1 } }}
                onClick={() => remove(index)}
              >
                <DeleteIcon sx={{ color: 'red' }} />
              </Button>
            </Tooltip>
          </Box>
          {errors?.sendInvitations?.[index]?.email && (
            <Typography sx={{ color: 'red', mt: 1, ml: 1 }}>
              {errors?.sendInvitations?.[index]?.email.message}
            </Typography>
          )}
        </Box>
      ))}
      <Button
        sx={{ fontSize: '12px' }}
        onClick={() => append({ email: '' })}
      >
        <AddCircleOutlineIcon sx={{ mr: 0.5, fontSize: '18px' }} />
        {t('ADD_ANOTHER')}
      </Button>
    </>
  );
};

export default InvitationForm;
