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

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

interface TocProps {
  novel: string;
  chapter: string;
  className?: string;
  onChangeSettings: (type?: string) => void;
}

const Toc = (props: TocProps) => {
  const { novel, chapter, className, onChangeSettings } = props;

  const { data: { data: chapters } = { data: null } } = useGet<ChapterListData>(
    `/api/novel/${novel}/chapters`
  );

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

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

      const list: JSX.Element[] = [];
      const len = Math.min(limit + offset, chapters.chapters.length);
      for (let i = offset; i < len; i++) {
        const item = chapters.chapters[i];
        list.push(
          <li
            key={item.id}
            className={clsx({
              [styles["current"]]: item.uri === `${novel}/${chapter}`,
            })}
          >
            <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;
    },
    [chapter, chapters, novel, 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 href="/icons.svg#close"></use>
          </svg>
        </button>
      </div>
      {chapters ? (
        <VirtualScroll
          component="ol"
          itemHeight={32}
          total={chapters.chapters.length}
          getItems={getTocItem}
          className={styles["toolbar-scrollbar"]}
          startIndex={startIndex}
        />
      ) : null}
    </div>
  );
};

export default Toc;
