import { useMutation, useQuery } from 'react-query';

import { useModal } from '@material-hu/hooks/useModal';

import HTMLBody from '@material-hu/components/composed-components/HTMLBody';
import Dialog from '@material-hu/components/design-system/Dialog';
import { useAuth } from 'src/contexts/JWTContext';
import useGeneralError from 'src/hooks/useGeneralError';
import useHuGoTheme from 'src/hooks/useHuGoTheme';
import {
  getTermsAndConditions,
  acceptTermsAndConditions,
} from 'src/services/authService';
import { useLokaliseTranslation } from 'src/utils/i18n';
import { initialPopupKeys } from 'src/components/dashboard/initialPopups/queries';

const TermsAndCondition = () => {
  const { t } = useLokaliseTranslation('web_only');
  const showGeneralError = useGeneralError();
  const { user, instance, acceptedTermsAndConditions } = useAuth();
  const HugoThemeProvider = useHuGoTheme();

  const { data: dataTermsAndCondition } = useQuery({
    queryKey: initialPopupKeys.termsAndConditions(),
    queryFn: getTermsAndConditions,
    select: response => response.data,
    onSuccess: response => {
      if (response) showTermsAndConditionsModal();
    },
    enabled:
      !user?.lastTermsAndConditionsAccepted && instance?.hasTermsAndConditions,
  });

  const {
    mutate: acceptTermsAndConditionsMutation,
    isLoading: isAcceptingTermsAndConditions,
  } = useMutation({
    mutationFn: acceptTermsAndConditions,
    onSuccess: () => acceptedTermsAndConditions?.(),
    onError: err =>
      showGeneralError(
        err,
        t('initial_popups.error_accept_terms_and_conditions'),
      ),
  });

  const handleAcceptTermsAndConditions = async () => {
    if (!dataTermsAndCondition?.id) return;

    acceptTermsAndConditionsMutation(dataTermsAndCondition.id, {
      onSettled: closeModal,
    });
  };

  const {
    modal: termsAndConditionsModal,
    showModal: showTermsAndConditionsModal,
    closeModal,
  } = useModal(
    () => (
      <Dialog
        title={t('initial_popups.terms_and_conditions', {
          instanceName: instance?.name,
        })}
        onClose={closeModal}
        body={<HTMLBody body={dataTermsAndCondition?.body || ''} />}
        primaryButtonProps={{
          onClick: handleAcceptTermsAndConditions,
          disabled: isAcceptingTermsAndConditions,
          loading: isAcceptingTermsAndConditions,
          children: t('general:accept'),
        }}
      />
    ),
    { disableEscapeKeyDown: true, fullWidth: true, maxWidth: 'sm' },
  );

  return <HugoThemeProvider>{termsAndConditionsModal}</HugoThemeProvider>;
};

export default TermsAndCondition;
