import clsx from "clsx";
import Link from "next/link";
import { useCallback, useMemo } from "react";
import VirtualScroll from "components/VirtualScroll";

import styles from "styles/chapter.module.scss";

interface TocProps {
  className?: string;
  currentUri: string;
  chapters: ChapterListData["chapters"];
  onChangeSettings: (type?: string) => void;
}

const Toc = (props: TocProps) => {
  const { currentUri, className, chapters, onChangeSettings } = props;

  const startIndex = useMemo(() => {
    const uri = currentUri;
    if (chapters && Array.isArray(chapters)) {
      const idx = chapters.findIndex((item) => item.uri === uri);
      if (idx > -1) {
        return idx;
      }
    }
    return 0;
  }, [currentUri, chapters]);

  const getTocItem = useCallback(
    (offset: number, limit: number) => {
      if (!chapters) return [];

      const list: JSX.Element[] = [];
      const len = Math.min(limit + offset, chapters.length);
      for (let i = offset; i < len; i++) {
        const item = chapters[i];
        list.push(
          <li
            key={item.id}
            className={clsx({
              [styles["current"]]: item.uri === currentUri,
            })}
          >
            <Link
              href={`/novel/${item.uri}`}
              title={item.name}
              key={item.id}
              onClick={() => onChangeSettings && onChangeSettings("")}
            >
              {/* <i>{i + 1}</i> */}
              {/* <strong>{item.name}</strong> */}
              {item.name}
            </Link>
          </li>
        );
      }
      return list;
    },
    [chapters, currentUri, onChangeSettings]
  );

  return (
    <div className={clsx(styles["toolbar-inner"], className)}>
      <div className={styles["toolbar-display-title"]}>
        Chapters
        <button
          className={styles["btn-close"]}
          onClick={() => onChangeSettings("")}
        >
          <svg className={styles["icon-close"]}>
            <use xlinkHref="/icons.svg#close"></use>
          </svg>
        </button>
      </div>
      {chapters ? (
        <VirtualScroll
          component="ol"
          itemHeight={32}
          total={chapters.length}
          getItems={getTocItem}
          className={styles["toolbar-scrollbar"]}
          startIndex={startIndex}
        />
      ) : null}
    </div>
  );
};

export default Toc;
