import { useEffect, useState } from 'react';
import { useParams } from 'react-router-dom'
import { Service } from '../Utils/HTTP';
import { useSelector } from 'react-redux';
import { Button, Box, Paper } from '@mui/material'
import { Document, Page, pdfjs } from 'react-pdf/dist/esm/entry.webpack';
// import 'react-pdf/dist/esm/Page/AnnotationLayer.css';
import 'react-pdf/dist/esm/Page/AnnotationLayer.css';
import 'react-pdf/dist/esm/Page/TextLayer.css';

const Cargando = () => <div><h2>loading...</h2></div>

// Create Document Component
const MyDocument = (props) => {

  let { pdf } = props;
  const [numPages, setNumPages] = useState(null);
  const [pageNumber, setPageNumber] = useState(1);

  function onDocumentLoadSuccess({ numPages }) {
    console.log('numero de pagians', numPages)
    setNumPages(numPages);
  }

  function onLoadError(error) {
    console.log('error: ', error)
  }

  return (
    <div>
      <div className="pdf_controls">
        <Button variant="contained" onClick={() => pageNumber > 1 ? setPageNumber(pageNumber - 1) : null} >
          Anterior
        </Button>
        <Button style={{ margin: 5 }} variant="contained" onClick={() => pageNumber + 1 <= numPages   ? setPageNumber(pageNumber + 1) : null} >
          Siguiente
        </Button>

        <p>
          Página {pageNumber} de {numPages}
        </p>

      </div>

      <div className="Example__container__document">
        <Document renderMode="canvas" file={pdf.data} onLoadSuccess={onDocumentLoadSuccess} onLoadError={onLoadError}>
          <Page width={800} pageNumber={pageNumber} loading={<Cargando />} />
        </Document>
      </div>
    </div>
  )
};


export function Resultados() {

  let { id } = useParams();
  let auth = useSelector((state) => state.token)
  let [pdf, setPdf] = useState(null);

  useEffect(() => {

    let url = `/report/cleaverResult/${id}?output=pdf`
    let rest = new Service(url);

    pdfjs.GlobalWorkerOptions.workerSrc = `https://cdnjs.cloudflare.com/ajax/libs/pdf.js/${pdfjs.version}/pdf.worker.js`;

    rest
      .getBlob(auth.token)
      .then(blob => setPdf(blob))
      .catch(error => console.log({ error }))

  }, [auth, id])

  return (
    <div className="content-section">
      <div className="main">
        <Box sx={{ width: '100%' }}>
          <Paper elevation={0} sx={{ mb: 2, padding: 2, height: '100%', minHeight: '95vh', boxShadow: 'none !important' }}>
            <h1>Resultados {id}</h1>
            <hr />
            {
              pdf ?
                <MyDocument pdf={pdf} />
                : <div> <h5> loading...</h5></div>
            }
          </Paper>
        </Box>
      </div>
    </div>
  )
}
