/**
 * @Move (SQCY)
 * Only used by the Insights module - move to Insights/
 */
import { useModal } from '@material-hu/hooks/useModal';

import * as topicsService from 'src/services/topicsService';
import { Topic } from 'src/types/topics';
import { download } from 'src/utils/filesUtils';
import { useLokaliseTranslation } from 'src/utils/i18n';

import ReportButton from 'src/components/ReportButton';

import DownloadingModal from '../DownloadingModal';
import ReportFilter from '../ReportFilter';

type Props = {
  topic: Partial<Topic>;
  includeSegmentationTooltip?: string;
};

const TopicReportButton = ({ topic, includeSegmentationTooltip }: Props) => {
  const { t } = useLokaliseTranslation('backoffice_only');

  const {
    modal: downloadingModal,
    showModal: showDownloadingModal,
    closeModal: closeDownloadingModal,
  } = useModal(
    DownloadingModal,
    { maxWidth: 'sm', fullWidth: true },
    { extended: true },
  );

  const handleDownloadReport = async (
    minDate?: string,
    maxDate?: string,
    includedGroups = [],
    includedUserFields = [],
  ) => {
    showDownloadingModal();
    const { data } = await topicsService.getTopicReport(
      topic.id,
      minDate,
      maxDate,
      includedGroups,
      includedUserFields,
    );
    download(data, `${topic.name}.xlsx`);
    closeDownloadingModal();
  };

  const {
    modal: reportModal,
    showModal: showReportModal,
    closeModal: closeReportModal,
  } = useModal(() => (
    <ReportFilter
      onSave={handleDownloadReport}
      onClose={closeReportModal}
      showUserFields
      includeUserFieldsTooltip={t(
        'backoffice_only:report_filter.include_user_fields_tooltip',
      )}
      includeSegmentationTooltip={includeSegmentationTooltip}
      dateFilterTooltip={t(
        'backoffice_only:topic_report_button.date_filter_tooltip',
      )}
    />
  ));

  return (
    <>
      {reportModal}
      {downloadingModal}
      <ReportButton
        onDownloadReport={() => handleDownloadReport()}
        onFilterReport={showReportModal}
      />
    </>
  );
};

export default TopicReportButton;
