import NovelCover from "components/NovelCover";
import { delHistoryItem, putHistoryItem } from "libs/db/history";
import Link from "next/link";

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

interface ItemProps {
  type: string;
  data: HistoryItem;
  onRemoved: () => void;
}

export default function Item({ type, data, onRemoved }: ItemProps) {
  const isHistory = type === "History";
  const url = `/novel/${isHistory ? data.chapterUri : data.uri}`;

  const handleRemoveItem = () => {
    const item = { ...data };
    if (isHistory) {
      item.isReading = 0;
    } else {
      item.isFavorite = 0;
    }

    (!item.isReading && !item.isFavorite
      ? delHistoryItem(data.uri)
      : putHistoryItem(data)
    ).then(onRemoved);
  };

  return (
    <li key={data.uri} className={styles.item}>
      <NovelCover
        className={styles.cover}
        component={Link}
        href={url}
        title={`${data.name} ${data.chapterName}`}
        src={data.img}
      />
      <div className={styles.body}>
        <div className={styles.title}>
          <Link href={url}>{data.name}</Link>
        </div>
        <div className={styles.progressTitle}>
          <Link href={url}>
            You have read {data.chapterIndex}/{data.chapterCount}
          </Link>
        </div>
        <div role="progressbar" className={styles.progressbar}>
          <div
            style={{
              width: `${(data.chapterIndex / data.chapterCount) * 100}%`,
            }}
          ></div>
        </div>
        <div className={styles.btns}>
          <Link className={styles.btn} href={url}>
            Continue Reading
          </Link>
        </div>
      </div>
      <button
        className={styles.close}
        onClick={handleRemoveItem}
        title={isHistory ? "Remove History" : "Remove Favorite"}
      >
        <svg>
          <use xlinkHref="/icons.svg#close"></use>
        </svg>
      </button>
    </li>
  );
}
