import EmptyResult from "components/EmptyResult";
import Pagination from "components/Pagination";
import useDbList from "libs/hooks/useDbList";
import Link from "next/link";

import styles from "./index.module.scss";
import Item from "./Item";

interface LibrayListProps {
  type: string;
}

export default function LibrayList({ type }: LibrayListProps) {
  const isHistory = type === "History";
  const [historyList, historyPages, fetchHistory] = useDbList(
    "history",
    isHistory ? "historyIsReading" : "historyIsFavorite",
    "prev",
    isHistory
      ? [
          [1, 0],
          [1, new Date()],
        ]
      : [1, 1]
  );

  const handlePageChange = (
    event: React.ChangeEvent<unknown>,
    value: number
  ) => {
    fetchHistory(value - 1);
  };

  const refreshList = () => {
    fetchHistory(historyPages.page);
  };

  return (
    <>
      {historyList.length ? (
        <ul className={styles.list}>
          {historyList.map((item) => (
            <Item
              key={item.uri}
              data={item}
              type={type}
              onRemoved={refreshList}
            />
          ))}
        </ul>
      ) : (
        <EmptyResult
          icon={isHistory ? "browseGallery" : "autoStories"}
          title={
            isHistory
              ? "You have no read history."
              : "You haven't added any books yet."
          }
        >
          <p>
            <Link href="/">EXPLORE NOW</Link>
          </p>
        </EmptyResult>
      )}
      {historyPages.total > historyPages.pageSize ? (
        <Pagination
          className="mt-5"
          count={Math.ceil(historyPages.total / historyPages.pageSize)}
          page={historyPages.page}
          onChange={handlePageChange}
        />
      ) : null}
    </>
  );
}
