import BackIcon from '@mui/icons-material/ArrowBack';
import NavigateBeforeIcon from '@mui/icons-material/NavigateBefore';
import NavigateNextIcon from '@mui/icons-material/NavigateNext';
import { AppBar, Backdrop, Box, Button, TextField, Toolbar, Typography } from '@mui/material';
import { FC, useEffect, useState } from 'react';
import { IList, useData } from '../../contexts/DataContext';
import { useRouter } from '../../routers/Router';

const PDFPage: FC = () => {
  const { goBack, getProps } = useRouter();
  const { entry } = getProps() as { entry: IList };
  const { file, isLoading, load } = useData();

  const [currentPage, setCurrentPage] = useState(1);
  const [pageJump, setPageJump] = useState('1');

  useEffect(() => {
    load(`${entry.name}\\${currentPage}.png`);
  }, [currentPage]);

  return (
    <Box>
      <AppBar position="sticky">
        <Toolbar>
          <Button startIcon={<BackIcon htmlColor="white" />} onClick={() => goBack()}>
            <Typography variant="h5" color="#fff">
              Back
            </Typography>
          </Button>
          <Typography variant="h5" marginLeft={2} component="div" sx={{ flexGrow: 1 }}>
            {entry.name}
          </Typography>
          <TextField
            variant="filled"
            value={pageJump}
            sx={{ input: { color: '#fff' }, width: '100px' }}
            onChange={(e) => setPageJump(e.target.value)}
          />
          <Button
            onClick={() => {
              try {
                let page = Number.parseInt(pageJump);
                if (isNaN(page)) page = currentPage;
                page = Math.max(1, Math.min(entry.pages, page));
                setCurrentPage(page);
                setPageJump(`${page}`);
              } catch (e) {
                console.warn(e);
              }
            }}
          >
            <Typography variant="h5" color="#fff">
              Go to
            </Typography>
          </Button>
          <Button onClick={() => setCurrentPage((prev) => (prev > 1 ? prev - 1 : prev))}>
            <NavigateBeforeIcon htmlColor="white" fontSize="large" />
          </Button>
          <Typography variant="h5">
            {currentPage}/{entry.pages}
          </Typography>
          <Button onClick={() => setCurrentPage((prev) => (prev < entry.pages ? prev + 1 : prev))}>
            <NavigateNextIcon htmlColor="white" fontSize="large" />
          </Button>
        </Toolbar>
      </AppBar>
      {isLoading ? (
        <Backdrop sx={{ color: '#fff', zIndex: (theme) => theme.zIndex.drawer + 1 }} open>
          <Typography variant="h1">Loading...</Typography>
        </Backdrop>
      ) : (
        <Box>
          <img src={`data:image/png;base64,${file}`} width="100%" />
        </Box>
      )}
    </Box>
  );
};

export default PDFPage;
