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, useRef, useState } from 'react';
import { v4 } from 'uuid';
import { IList, useData } from '../../contexts/DataContext';
import { useRouter } from '../../routers/Router';

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

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

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

  return (
    <Box>
      <AppBar position="sticky">
        <Toolbar>
          <Button startIcon={<BackIcon htmlColor="white" />} onClick={() => goBack({ path })}>
            <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) => {
              e.stopPropagation();
              setPageJump(e.target.value);
            }}
            onFocus={() => Coherent.trigger('FOCUS_INPUT_FIELD', guid, '', '', '', false)}
            onBlur={() => Coherent.trigger('UNFOCUS_INPUT_FIELD', guid)}
          />
          <Button
            onClick={() => {
              try {
                let page = Number.parseInt(pageJump);
                if (isNaN(page)) page = currentPage;
                page = Math.max(1, Math.min(entry.pages ?? 0, 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 ?? 0) ? 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;
