import axios from "axios";
import { useEffect, useRef, useState } from "react";
import { useNavigate, useParams } from "react-router";
import "./reader.css";
import OutlinedButton from "../md-components/OutlinedButton";
import FilledButton from "../md-components/FilledButton";
import Contents from "../components/contents/Contents";
import Icon from "../md-components/Icon";
import { Link } from "react-router-dom";
import Skeleton from "react-loading-skeleton";
import LinearProgress from "../md-components/LinearProgress";
import {
  addBook,
  getBook,
  getReadBook,
  putReadBook,
  removeBook,
  saveReadBook,
  updateReadBook,
} from "../db";
import IconButton from "../md-components/IconButton";
import ReaderFB2 from "./ReaderFB2";

const Reader = () => {
  const { id } = useParams();
  const navigate = useNavigate();

  const [isLocal, setIsLocal] = useState(false);
  const [onBookshelf, setOnBookshelf] = useState(false);
  const [bookInfo, setBookInfo] = useState(false);
  const [contents, setContents] = useState([]);
  const [saving, setSaving] = useState(false);
  const [shelving, setShelving] = useState(false);
  const [pdfURL, setPdfURL] = useState(false);

  async function loadBook() {
    let readBook = await getReadBook(id);
    if (readBook) {
      setOnBookshelf(readBook.onBookshelf === true);
    }
    let caches = undefined;
    let localFile = undefined;
    if (window.caches !== undefined) {
      caches = await window.caches.open("books");
      localFile = await caches.match(`/api/book/${id}/reader`);
    }
    let localBook = await getBook(id);
    if (localBook !== undefined && localFile !== undefined) {
      setIsLocal(true);
      setContents(localBook.contents);
      setBookInfo(localBook);

      let blob = await localFile.blob();
      let pdfBlob = new Blob([blob], { type: "application/pdf" });
      console.log(pdfBlob);
      setPdfURL(URL.createObjectURL(pdfBlob));
    } else {
      if (!window.onLine) {
        localStorage.removeItem("lastReadBook");
        navigate("/offline");
      }
      setIsLocal(false);
      axios
        .get(`/book/${id}`)
        .then((res) => setBookInfo(res.data))
        .catch(() => navigate("/notfound"));
      axios.get(`/book/${id}/contents`).then((res) => setContents(res.data));
      setPdfURL(`/api/book/${id}/reader`);
    }
    console.log(bookInfo);
    localStorage.setItem("lastReadBook", id);
  }
  useEffect(() => {
    loadBook();
  }, [id]);
  async function saveBook() {
    setSaving(true);
    let caches = await window.caches.open("books");
    await caches.add(`/api/book/${id}/reader`);
    await addBook(id, bookInfo, contents);
    await saveReadBook(id, true);
    setIsLocal(true);
    setSaving(false);
    console.log("save");
  }
  async function deleteBook() {
    let caches = await window.caches.open("books");
    await caches.delete(`/api/book/${id}/reader`);
    await removeBook(id);
    await saveReadBook(id, false);
    setIsLocal(false);
  }

  return (
    <>
      <h1 style={{ display: "flex", marginBottom: 0, gap: "10px" }}>
        <span className="truncate">
          {bookInfo.title || (
            <Skeleton width={300} style={{ display: "inline-block" }} />
          )}{" "}
        </span>
        {isLocal ? (
          <Icon style={{ lineHeight: "38px", height: "100%" }}>cloud_off</Icon>
        ) : (
          <></>
        )}
      </h1>
      <span>
        {bookInfo.authors ? (
          bookInfo.authors
            .map((author) => (
              <Link
                to={"/search?author=" + author.id}
                style={{ color: "var(--md-sys-color-on-background)" }}
              >
                {author.name}
              </Link>
            ))
            .reduce((prev, curr) => [prev, ", ", curr])
        ) : bookInfo.authors === null ? (
          <span>Автор неизвестен</span>
        ) : (
          <Skeleton width={350} />
        )}
      </span>
      <div style={{ display: "flex", gap: "10px" }} className="flex mt-4">
        <Link to={`/book/${id}`} className="reader_action_button">
          <FilledButton style={{ width: "100%" }}>
            <Icon slot="icon">info</Icon>
            Информация
          </FilledButton>
        </Link>
        {isLocal ? (
          <OutlinedButton onClick={deleteBook} className="reader_action_button">
            <Icon slot="icon">delete</Icon>
            Удалить с устройства
          </OutlinedButton>
        ) : (
          <OutlinedButton
            onClick={saveBook}
            className="reader_action_button"
            disabled={window.caches === undefined || saving}
          >
            <Icon slot="icon">cloud</Icon>
            {saving ? "Сохранение..." : "Сохранить локально"}
          </OutlinedButton>
        )}
        {/* <OutlinedButton
          className="reader_action_button"
          onClick={async () => {
            setShelving(true);
            let caches = await window.caches.open("bookCovers");
            if (onBookshelf) {
              await caches.delete(`/api/book/${id}/cover`);
            } else {
              await caches.add(`/api/book/${id}/cover`);
            }
            putReadBook(id, !onBookshelf, bookInfo);
            setOnBookshelf(!onBookshelf);
            setShelving(false);
          }}
          disabled={shelving}
        >
          <Icon slot="icon">book</Icon>
          {shelving
            ? "Сохранение..."
            : onBookshelf
            ? "Убрать с полки"
            : "На полку"}
        </OutlinedButton> */}
      </div>
      {bookInfo.filetype === "fb2" ? (
        <ReaderFB2 />
      ) : pdfURL ? (
        <embed className="h-[calc(100vh-15px)]" src={pdfURL}></embed>
      ) : (
        <>
          <LinearProgress indeterminate />
          <span>Загрузка...</span>
        </>
      )}
    </>
  );
};

export default Reader;
