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

import { IconDownload } from '@material-hu/icons/tabler';
import Card from '@material-hu/mui/Card';
import CardMedia from '@material-hu/mui/CardMedia';
import Stack from '@material-hu/mui/Stack';
import * as animations from '@material-hu/utils/animations';

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

import useHuGoTheme from 'src/hooks/useHuGoTheme';
import useGetDocument from 'src/pages/dashboard/documents/hooks/useGetDocument';
import useGetDocumentUrl from 'src/pages/dashboard/documents/hooks/useGetDocumentUrl';
import { getBlobCloudfrontDocument, isSecureFile } from 'src/utils/documents';
import { downloadBlob } from 'src/utils/files';
import { useLokaliseTranslation } from 'src/utils/i18n';
import { FileExtensions } from 'src/constants/filesPreview';
import FocusNavbar from 'src/components/FocusNavbar';

import { IMG_DOCUMENT_EXTENSIONS } from './constants';

const Document = () => {
  const [isDownloading, setIsDownloading] = useState(false);

  const navigate = useNavigate();
  const HuGoThemeProvider = useHuGoTheme();

  const { documentId } = useParams();
  const { t } = useLokaliseTranslation('documents');

  const { data: document, isLoading: isLoadingRequest } = useGetDocument({
    documentId,
  });

  const { data: documentUrl, isLoading: isLoadingUrl } = useGetDocumentUrl({
    source: document?.source,
  });

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

  const handleDownload = async () => {
    if (!document) return;

    if (isSecureFile(document.source)) {
      setIsDownloading(true);
      const blobPromise = await getBlobCloudfrontDocument(document.source);
      blobPromise && downloadBlob(blobPromise, document.name);
      setIsDownloading(false);
    } else {
      window.open(document.source, '_blank', 'noreferrer');
    }
  };

  const extension = document?.extension.toLowerCase() || '';
  const isPdf = extension === FileExtensions.PDF;
  const isImage = IMG_DOCUMENT_EXTENSIONS.includes(extension);

  return (
    <HuGoThemeProvider>
      <FocusNavbar
        sx={{ animation: `${animations.fadeIn} 0.3s ease` }}
        navbarProps={{
          title: document?.name || '',
          onClick: closePage,
          sx: { height: 64, p: 2 },
          extraButtons: (
            <Button
              variant="secondary"
              startIcon={<IconDownload />}
              onClick={handleDownload}
              loading={isDownloading}
            >
              {t('download')}
            </Button>
          ),
        }}
        loadingProps={{
          isLoading: isLoadingRequest || isLoadingUrl,
        }}
        content={
          !isLoadingUrl && (
            <>
              {isPdf && (
                <PdfVisualizer
                  file={documentUrl || ''}
                  slotProps={{
                    pdfDimensions: { baseWidth: 700 },
                  }}
                />
              )}

              {isImage && (
                <Stack
                  sx={{
                    alignItems: 'center',
                    justifyContent: 'center',
                    height: '100%',
                    p: 2,
                  }}
                >
                  <Card
                    sx={{
                      backgroundColor: theme =>
                        theme.palette.new.background.layout.tertiary,
                      padding: 2,
                      borderRadius: 2,
                    }}
                  >
                    <CardMedia
                      component="img"
                      src={documentUrl || ''}
                      sx={{
                        height: 'fit-content',
                        width: 'fit-content',
                        maxWidth: '100%',
                        maxHeight: '100%',
                        objectFit: 'contain',
                        borderRadius: 1,
                      }}
                    />
                  </Card>
                </Stack>
              )}
            </>
          )
        }
      />
    </HuGoThemeProvider>
  );
};

export default Document;
