import BackIcon from '@mui/icons-material/ArrowBack';
import BookmarkIcon from '@mui/icons-material/Bookmark';
import BookmarkBorderIcon from '@mui/icons-material/BookmarkBorder';
import DeleteIcon from '@mui/icons-material/Delete';
import NavigateBeforeIcon from '@mui/icons-material/NavigateBefore';
import NavigateNextIcon from '@mui/icons-material/NavigateNext';
import { AppBar, Backdrop, Box, Button, Grid, Stack, 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, bookMarks, isLoading, isSaving, load, addBookMark, removeBookMark } = useData();

  const guid1 = useRef(v4());
  const guid2 = useRef(v4());

  const [currentPage, setCurrentPage] = useState(1);
  const [pageJump, setPageJump] = useState('1');
  const [drawerOpen, setDrawerOpen] = useState(false);
  const [markName, setMarkName] = useState('');

  useEffect(() => {
    load(`${path}/${entry.name}/${currentPage}.bjpg`);
  }, [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" fontWeight="bold" 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', guid1, '', '', '', false)}
            onBlur={() => Coherent.trigger('UNFOCUS_INPUT_FIELD', guid1)}
          />
          <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>
          <Button onClick={() => setDrawerOpen(true)}>
            {bookMarks.findIndex((mark) => mark.page === currentPage) !== -1 ? (
              <BookmarkIcon htmlColor="white" fontSize="large" />
            ) : (
              <BookmarkBorderIcon 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/jpg;base64,${file}`} width="100%" />
        </Box>
      )}
      {drawerOpen && (
        <Backdrop
          sx={{ color: '#fff', zIndex: (theme) => theme.zIndex.drawer + 1 }}
          open
          onClick={() => setDrawerOpen(false)}
        >
          <Box width="33%" position="absolute" right={0} top={0} bottom={0} onClick={(e) => e.stopPropagation()}>
            <AppBar position="sticky" sx={{ marginBottom: '44px' }}>
              <Toolbar>
                <TextField
                  variant="filled"
                  value={markName}
                  sx={{ input: { color: '#fff' }, flexGrow: 1 }}
                  onChange={(e) => {
                    e.stopPropagation();
                    setMarkName(e.target.value);
                  }}
                  onFocus={() => Coherent.trigger('FOCUS_INPUT_FIELD', guid2, '', '', '', false)}
                  onBlur={() => Coherent.trigger('UNFOCUS_INPUT_FIELD', guid2)}
                />
                <Button
                  disabled={isSaving}
                  onClick={() => {
                    if (markName !== '') {
                      addBookMark(`${path}/${entry.name}`, { page: currentPage, title: markName });
                      setMarkName('');
                    }
                  }}
                >
                  <Typography variant="h5" color="#fff">
                    Add
                  </Typography>
                </Button>
              </Toolbar>
            </AppBar>
            <virtual-scroll
              direction="y"
              style={{ height: 'calc(100% - 110px)', backgroundColor: 'var(--backgroundColorContrastedPanel)' }}
            >
              <Stack spacing={2}>
                {bookMarks.map((mark, index) => (
                  <Grid
                    key={index}
                    bgcolor="primary.main"
                    onClick={() => setCurrentPage(mark.page)}
                    container
                    padding={1}
                    height={73}
                  >
                    <Grid item xs={9} padding={0}>
                      <Box display="flex" alignItems="center" height="100%">
                        <Typography variant="h5" overflow="ellipsis">
                          {mark.title}
                        </Typography>
                      </Box>
                    </Grid>
                    <Grid item xs={3} padding={0} display="flex" alignItems="center">
                      <Button
                        onClick={(e) => {
                          e.stopPropagation();
                          removeBookMark(`${path}/${entry.name}`, index);
                        }}
                      >
                        <DeleteIcon htmlColor="white" fontSize="large" />
                      </Button>
                    </Grid>
                  </Grid>
                ))}
              </Stack>
            </virtual-scroll>
          </Box>
        </Backdrop>
      )}
    </Box>
  );
};

export default PDFPage;
