import { useNoteStore } from "@/state/Stores";
import { observer } from "mobx-react-lite";
import { useMemo } from "react";
import Pagination from "react-bootstrap/Pagination";
import { useIntParam } from "taehui-lib/fe-utilities";

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

  const { param: page, setParam: setPage } = useIntParam("page", 1);

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

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

  if (lastPage === 0) {
    return null;
  }

  return (
    <Pagination>
      <Pagination.First
        disabled={isLowestPage}
        onClick={() => {
          setPage(1);
        }}
      />
      <Pagination.Prev
        disabled={isLowestPage}
        onClick={() => {
          setPage(page - 1);
        }}
      />
      {pages.map((targetPage) => (
        <Pagination.Item
          key={targetPage}
          active={targetPage === page}
          onClick={() => {
            setPage(targetPage);
          }}
        >
          {targetPage}
        </Pagination.Item>
      ))}
      <Pagination.Next
        disabled={isHighestPage}
        onClick={() => {
          setPage(page + 1);
        }}
      />
      <Pagination.Last
        disabled={isHighestPage}
        onClick={() => {
          setPage(lastPage);
        }}
      />
    </Pagination>
  );
});
