import { lazy, Suspense } from 'react';

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

import Button from '@material-hu/components/design-system/Buttons/Button';
import Skeleton from '@material-hu/components/design-system/Skeleton';

import { useDownloadSessionReport } from 'src/pages/dashboard/Learning/Sessions/hooks/useDownloadSessionReport';
import { type DownloadReportFnParams } from 'src/pages/dashboard/Learning/Sessions/types';
import { useLokaliseTranslation } from 'src/utils/i18n';

const DownloadReportsModal = lazy(() => import('./DownloadReportsModal'));

type DownloadReportButtonProps = {
  sessionId?: number;
};

export const DownloadReportButton = ({
  sessionId,
}: DownloadReportButtonProps) => {
  const { t } = useLokaliseTranslation('learning');

  const { mutate: downloadReport, isLoading } =
    useDownloadSessionReport(sessionId);

  const handleDownloadReport = (params: DownloadReportFnParams) => {
    downloadReport({
      email: params.email,
      includeGroups: params.includeGroups,
      includeUserFields: params.includeUserFields,
    });
  };

  const {
    closeModal,
    showModal: handleShowModal,
    modal,
  } = useModal(
    () => (
      <Suspense
        fallback={
          <Skeleton
            height={360}
            width="100%"
          />
        }
      >
        <DownloadReportsModal
          onClose={closeModal}
          loading={isLoading}
          onDownloadReport={handleDownloadReport}
        />
      </Suspense>
    ),
    {
      fullWidth: true,
      maxWidth: 'sm',
      sx: { '& .MuiDialogContent-root': { pt: 0 } },
    },
  );

  return (
    <>
      {modal}
      <Button
        variant="contained"
        onClick={handleShowModal}
        disabled={!sessionId}
      >
        {t('general:download')}
      </Button>
    </>
  );
};
