import { useMemo } from "react";
import { observer } from "mobx-react-lite";
import { Pagination, PaginationItem, PaginationLink } from "reactstrap";
import { usePage } from "taehui-ts/fe-utility";

import { useNoteStore } from "src/Stores";

const PositionInput = observer(() => {
  const { pageUnit, lastPage } = useNoteStore();

  const { page, setPage } = usePage();

  const targetPages = useMemo(() => {
    const targetPages = [];
    for (
      let i = 1 + Math.floor((page - 1) / pageUnit) * pageUnit;
      i <=
      Math.min(
        lastPage,
        Math.floor((page - 1) / pageUnit) * pageUnit + pageUnit,
      );
      ++i
    ) {
      targetPages.push(i);
    }
    return targetPages;
  }, [lastPage, page, pageUnit]);

  const isLowestPage = useMemo(() => page === 1, [page]);
  const isHighestPage = useMemo(() => page === lastPage, [lastPage, page]);

  return (
    <Pagination>
      <PaginationItem disabled={isLowestPage}>
        <PaginationLink
          first
          onClick={() => {
            setPage(1);
          }}
        />
      </PaginationItem>
      <PaginationItem disabled={isLowestPage}>
        <PaginationLink
          previous
          onClick={() => {
            setPage(page - 1);
          }}
        />
      </PaginationItem>
      {targetPages.map((targetPage) => (
        <PaginationItem key={targetPage} active={targetPage === page}>
          <PaginationLink
            onClick={() => {
              setPage(targetPage);
            }}
          >
            {targetPage}
          </PaginationLink>
        </PaginationItem>
      ))}
      <PaginationItem disabled={isHighestPage}>
        <PaginationLink
          next
          onClick={() => {
            setPage(page + 1);
          }}
        />
      </PaginationItem>
      <PaginationItem disabled={isHighestPage}>
        <PaginationLink
          last
          onClick={() => {
            setPage(lastPage);
          }}
        />
      </PaginationItem>
    </Pagination>
  );
});

export default PositionInput;
