import { forwardRef } from 'react';

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

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

import { Page } from 'src/config/react-pdf';
import {
  PageDimensions,
  SectionComponent,
} from 'src/pages/dashboard/serviceManagement/types';

import { usePdfCompletion } from '../contexts/PdfFormCompletionProvider';

import FieldWrapper from './InputFields/FieldWrapper';

type Props = {
  pageIndex: number;
  pageDimensions: PageDimensions;
  fields: SectionComponent[];
};

const PdfPageWithOverlay = forwardRef<HTMLDivElement, Props>(
  ({ fields, pageIndex, pageDimensions }, ref) => {
    const { scale } = usePdfCompletion();

    return (
      <Stack
        ref={ref}
        style={{
          position: 'relative',
        }}
      >
        <Page
          loading={<HuSpinner centered />}
          pageNumber={pageIndex + 1}
          scale={scale}
          renderAnnotationLayer={false}
          renderTextLayer={false}
        />
        {/* Overlay layer aligned with the rendered page */}
        <Stack
          style={{
            position: 'absolute',
            inset: 0,
            overflow: 'visible',
          }}
        >
          {fields.map(f => {
            return (
              <FieldWrapper
                key={f.nameId}
                field={f}
                pageDimensions={pageDimensions}
              />
            );
          })}
        </Stack>
      </Stack>
    );
  },
);

PdfPageWithOverlay.displayName = 'PdfPageWithOverlay';

export default PdfPageWithOverlay;
