import { FC, useState } from 'react';
import { useQuery } from 'react-query';

import DialogContent from '@material-hu/mui/DialogContent';

import { useAuth } from 'src/contexts/JWTContext';
import useGeneralError from 'src/hooks/useGeneralError';
import { getNewFeatures } from 'src/services/authService';
import { useLokaliseTranslation } from 'src/utils/i18n';
import AcceptCancelDialog from 'src/components/AcceptCancelDialog';
import { initialPopupKeys } from 'src/components/dashboard/initialPopups/queries';
import HTMLBody from 'src/components/HTMLBody';

const NewFeatures: FC = () => {
  const [open, setOpen] = useState(true);

  const { t } = useLokaliseTranslation('web_only');
  const showGeneralError = useGeneralError();
  const { user } = useAuth();

  const dataFatures = useQuery(
    initialPopupKeys.features(),
    () => getNewFeatures(),
    {
      onError: err => showGeneralError(err, t('error_get_new_features')),
      enabled: user?.lastTermsAndConditionsAccepted,
    },
  );

  const newFeatures = dataFatures?.data?.data || undefined;

  const handleAccept = () => {
    setOpen(false);
  };

  const shouldOpenDialog = open && !!newFeatures && !newFeatures?.seen;

  return (
    <AcceptCancelDialog
      open={shouldOpenDialog}
      onAccept={handleAccept}
      enabledTitle={false}
    >
      <DialogContent
        dividers
        sx={{ borderTop: '0' }}
      >
        <HTMLBody body={newFeatures?.body} />
      </DialogContent>
    </AcceptCancelDialog>
  );
};

export default NewFeatures;
