import { useQuery } from 'react-query';
import { useNavigate, useParams } from 'react-router-dom';

import { useDrawerV2 } from '@material-hu/hooks/useDrawerV2';
import { IconDownload, IconPlus } from '@material-hu/icons/tabler';
import Container from '@material-hu/mui/Container';
import Stack from '@material-hu/mui/Stack';
import Typography from '@material-hu/mui/Typography';

import Button from '@material-hu/components/design-system/Buttons/Button';
import HuCircularProgress from '@material-hu/components/design-system/ProgressIndicators/Spinner';

import useHuGoTheme from 'src/hooks/useHuGoTheme';
import { appsKeys } from 'src/pages/dashboard/Apps/queries';
import * as jobsService from 'src/services/jobsService';
import { type AnyBulkUploadType } from 'src/types/bulk';
import { download } from 'src/utils/filesUtils';
import { useLokaliseTranslation } from 'src/utils/i18n';

import FocusView from 'src/components/FocusView';

import { BulkTable } from './components/BulkTable';
import { EmptyBulk } from './components/EmptyBulk';
import useDrawerUploader from './hooks/useDrawerUploader';
import { getDownloadTemplateService } from './utils';

type Props = {
  type: AnyBulkUploadType;
};

const LIMIT = 20;
const PAGE = 1;

const HuBulkUpload = ({ type }: Props) => {
  const { t } = useLokaliseTranslation('backoffice_only');
  const { id } = useParams();
  const navigate = useNavigate();
  const HuGoThemeProvider = useHuGoTheme();
  const { name, downloadService } = getDownloadTemplateService(type, t, id);

  const onBack = () => {
    navigate(-1);
  };

  const { drawer, showDrawer } = useDrawerV2(props =>
    useDrawerUploader({ ...props, type }),
  );

  const { data: jobs, isLoading } = useQuery(
    appsKeys.jobsByType(type),
    () => jobsService.getJobsByType(type, PAGE, LIMIT),
    {
      select: response => response.data,
    },
  );

  const handleDownloadTemplate = async () => {
    const { data } = await downloadService();
    download(data, name);
  };

  return (
    <HuGoThemeProvider>
      {drawer}
      <FocusView
        navbarProps={{
          title: t('backoffice_only:bulk_upload.bulk_upload', {
            context: type,
          }),
          onClick: onBack,
        }}
      >
        <Container
          maxWidth="md"
          sx={{ pt: 3 }}
        >
          <Stack
            sx={{
              flexDirection: 'row',
              justifyContent: 'space-between',
              pb: 2,
            }}
          >
            <Typography
              variant="globalM"
              fontWeight="fontWeightSemiBold"
            >
              {t('backoffice_only:bulk_upload.history')}
            </Typography>
            <Stack sx={{ flexDirection: 'row', gap: 2 }}>
              <Button
                startIcon={<IconDownload />}
                onClick={handleDownloadTemplate}
                variant="secondary"
              >
                {t('backoffice_only:bulk_upload.step_1_download')}
              </Button>
              <Button
                startIcon={<IconPlus />}
                sx={{ width: 'fit-content' }}
                variant="primary"
                onClick={() => showDrawer({})}
              >
                {t('backoffice_only:bulk_upload.new_bulk_upload')}
              </Button>
            </Stack>
          </Stack>
          {!isLoading && jobs && jobs.length > 0 && (
            <BulkTable
              jobs={jobs}
              type={type}
            />
          )}
          {!isLoading && jobs?.length === 0 && (
            <EmptyBulk onHandleDownloadTemplate={handleDownloadTemplate} />
          )}
          {isLoading && <HuCircularProgress centered />}
        </Container>
      </FocusView>
    </HuGoThemeProvider>
  );
};

export default HuBulkUpload;
