import { FC, useState } from 'react';

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

import DownloadIcon from '@material-hu/icons/material/Download';
import Box from '@material-hu/mui/Box';
import CircularProgress from '@material-hu/mui/CircularProgress';
import IconButton from '@material-hu/mui/IconButton';
import Tooltip from '@material-hu/mui/Tooltip';
import Typography from '@material-hu/mui/Typography';

import { Document, Page } from 'src/config/react-pdf';

import useGeneralError from 'src/hooks/useGeneralError';
import { useSecureFileUrl } from 'src/hooks/useSecureFileUrl';
import { getFormAnswer, fetchFormCompletedPdfBlob } from 'src/services/forms';
import { openBlob } from 'src/utils/files';
import { useLokaliseTranslation } from 'src/utils/i18n';

import PdfPaginator from 'src/components/dashboard/form/pdfForm/PdfPaginator';
import { formKeys } from 'src/components/dashboard/form/queries';
import GoBackButton from 'src/components/dashboard/GoBackButton';

const FormPdfAnswer: FC = () => {
  const { templateId, answerId } = useParams<{
    templateId: string;
    answerId: string;
  }>();
  const showGeneralError = useGeneralError();

  const queryClient = useQueryClient();

  const [currentPage, setCurrentPage] = useState(1);
  const [isLoadingPdf, setIsLoadingPdf] = useState(false);

  const navigate = useNavigate();
  const { t } = useLokaliseTranslation('forms');

  const { data } = useQuery(
    formKeys.answer(templateId!, answerId!),
    () => getFormAnswer(templateId, answerId),
    {
      onError: err => showGeneralError(err, t('NO_FORM_INFO')),
      enabled: !!answerId && !!templateId,
      select: res => res?.data,
    },
  );

  const handleDownload = async () => {
    if (!templateId || !answerId) return;
    try {
      setIsLoadingPdf(true);

      const pdfData = await queryClient.fetchQuery(
        formKeys.pdf.blob(templateId, answerId),
        () => fetchFormCompletedPdfBlob(templateId, answerId, true),
      );

      const { blob = null, blobUrl = null } = pdfData || {};

      openBlob(blob, blobUrl);
    } catch (err) {
      showGeneralError(err, t('ERROR_LOADING_PDF_REPORT'));
    } finally {
      setIsLoadingPdf(false);
    }
  };

  const title = data?.title;

  const {
    height: pdfHeight,
    width: pdfWidth,
    totalPages,
  } = data?.steps?.[0]?.sourceData || {};

  const goBack = () => navigate(-1);

  const fileUrl = useSecureFileUrl(data?.steps?.[0]?.sourceAnswered ?? '');

  return (
    <Box
      style={{
        display: 'flex',
        flexDirection: 'column',
        padding: '35px 120px',
      }}
    >
      <Box
        style={{
          display: 'flex',
          flexDirection: 'column',
          width: `${pdfWidth}px`,
          alignSelf: 'center',
        }}
      >
        <Box
          style={{
            display: 'flex',
            gap: '10px',
            justifyContent: 'space-between',
            alignItems: 'baseline',
          }}
        >
          <GoBackButton onClick={goBack} />
          <Typography
            maxWidth={pdfWidth ? pdfWidth - 250 : undefined}
            noWrap
            overflow="hidden"
            textOverflow="ellipsis"
            variant="h5"
          >
            {title}
          </Typography>
          <Tooltip title={t('DOWNLOAD_ANSWER')}>
            <IconButton
              aria-label={title}
              disabled={isLoadingPdf}
              onClick={handleDownload}
              color="primary"
            >
              {isLoadingPdf ? <CircularProgress size={16} /> : <DownloadIcon />}
            </IconButton>
          </Tooltip>
        </Box>
        {totalPages && (
          <PdfPaginator
            currentPage={currentPage}
            totalPages={totalPages}
            setCurrentPage={setCurrentPage}
          />
        )}
        {!!fileUrl && (
          <Document
            file={fileUrl}
            loading={<CircularProgress />}
          >
            <Page
              loading={<CircularProgress />}
              renderAnnotationLayer={false}
              width={pdfWidth}
              height={pdfHeight}
              pageNumber={currentPage}
            />
          </Document>
        )}
      </Box>
    </Box>
  );
};

export default FormPdfAnswer;
