import { useState } from 'react';
import { useForm } from 'react-hook-form';

import { useQuery } from 'react-query';

import useSnackbar from '@material-hu/components/design-system/Snackbar';

import { useAuth } from 'src/contexts/JWTContext';
import useFeatureFlag from 'src/hooks/useFeatureFlag';
import useGeneralError from 'src/hooks/useGeneralError';
import { getGroupMembersReport } from 'src/services/groups';
import { FeatureFlags } from 'src/types/featureFlags';
import { useLokaliseTranslation as useTranslation } from 'src/utils/i18n';

import { groupsKeys } from '../../../queries';
import { GroupMembersFormValues } from '../types';

const useGroupMembersReportDownload = (groupId: string) => {
  const [requestReportToggle, setRequestReportToggle] = useState(false);
  const showGeneralError = useGeneralError();
  const { enqueueSnackbar } = useSnackbar();
  const { t } = useTranslation(['group']);
  const { user } = useAuth();
  const isDownloadGroupMembersReportEnabled = useFeatureFlag(
    FeatureFlags.DOWNLOAD_GROUP_MEMBERS_REPORT,
  );
  const groupMembersReportDrawerForm = useForm<GroupMembersFormValues>({
    defaultValues: {
      email: user?.email || '',
    },
    mode: 'onChange',
  });

  const { watch } = groupMembersReportDrawerForm;
  const { email } = watch();

  useQuery(
    groupsKeys.groupMembersReport(groupId, email),
    () => {
      return getGroupMembersReport(groupId, email);
    },
    {
      enabled: requestReportToggle && !!isDownloadGroupMembersReportEnabled,
      onSettled: () => setRequestReportToggle(false),
      onError: (err: any) => {
        if (err.response.status) {
          enqueueSnackbar({
            title: t('group:report_in_progress'),
            variant: 'error',
          });
        } else if (err?.response?.data?.[0]?.isEmail) {
          enqueueSnackbar({
            title: t('group:invalid_email_web'),
            variant: 'error',
          });
        } else {
          showGeneralError(err);
        }
      },
      onSuccess: () => {
        enqueueSnackbar({
          title: t('group:email_sent_web'),
          variant: 'success',
        });
      },
    },
  );

  const handleReportSubmit = () => setRequestReportToggle(true);
  return {
    groupMembersReportDrawerForm,
    submitGroupMembersReport:
      groupMembersReportDrawerForm.handleSubmit(handleReportSubmit),
  };
};

export default useGroupMembersReportDownload;
