import { type FC, useState } from 'react';

import Stack from '@material-hu/mui/Stack';

import HuSpinner from '@material-hu/components/design-system/ProgressIndicators/Spinner';

import { Document, Page } from 'src/config/react-pdf';
import {
  type FormSection,
  type Task,
} from 'src/pages/dashboard/serviceManagement/types';
import { getBlobCloudfrontDocument } from 'src/utils/documents';
import { downloadBlob, downloadUrl } from 'src/utils/files';

import FullscreenPdfViewer from './FullscreenPdfViewer';

type Props = {
  formData: FormSection;
  taskData: Task;
};

const PdfFormAnswer: FC<Props> = ({ formData, taskData }) => {
  const [totalPages, setTotalPages] = useState(0);

  const [openFullscreenPdf, setOpenFullscreenPdf] = useState(false);
  const [initialPage, setInitialPage] = useState<number>(1);

  const pdfFileAsset = formData.pdfFileAsset;

  if (!pdfFileAsset) {
    return null;
  }

  const handleLoadSuccess = ({ numPages }: { numPages: number }) => {
    setTotalPages(numPages);
  };

  const handlePageClick = (page: number) => {
    setInitialPage(page);
    setOpenFullscreenPdf(true);
  };

  const handleDownload = async () => {
    downloadUrl(pdfFileAsset.url, pdfFileAsset.name);
    try {
      const blob = await getBlobCloudfrontDocument(pdfFileAsset.url);
      if (blob) {
        downloadBlob(blob, pdfFileAsset.name);
      }
    } catch (_err) {
      return null;
    }
  };

  const serviceItemName = taskData.catalogItem?.name;

  return (
    <Stack sx={{ width: 1, overflowX: 'auto' }}>
      {openFullscreenPdf && (
        <FullscreenPdfViewer
          open={openFullscreenPdf}
          file={pdfFileAsset.url}
          name={pdfFileAsset.name}
          headerTitle={serviceItemName}
          onDownload={handleDownload}
          onClose={() => setOpenFullscreenPdf(false)}
          initialPage={initialPage}
        />
      )}
      <Document
        file={pdfFileAsset.url}
        onLoadSuccess={handleLoadSuccess}
        loading={<HuSpinner centered />}
      >
        <Stack
          sx={{
            width: '100%',
            gap: 2,
            justifyContent: 'flex-start',
            alignItems: 'center',
          }}
        >
          {Array.from({ length: totalPages }, (_, i) => (
            <Stack
              key={i}
              onClick={() => handlePageClick(i + 1)}
              sx={{
                width: 'max-content',
                overflow: 'hidden',
                cursor: 'pointer',
                border: ({ palette }) =>
                  `1px solid ${palette.new.border.neutral.default}`,
                borderRadius: ({ shape }) => shape.borderRadiusM,
                '&:hover': {
                  border: ({ palette }) =>
                    `1px solid ${palette.new.border.neutral.brand}`,
                },
              }}
            >
              <Page
                pageNumber={i + 1}
                width={240}
                renderTextLayer={false}
                renderAnnotationLayer={false}
                scale={1}
                loading=""
              />
            </Stack>
          ))}
        </Stack>
      </Document>
    </Stack>
  );
};

export default PdfFormAnswer;
