import axios from "axios";
import { useEffect, useRef, useState } from "react";
import Skeleton from "react-loading-skeleton";
import BookCard from "../../components/bookCard/BookCard";
import Icon from "../../md-components/Icon";
import {
  getAllReadBooks,
  getBook,
  putReadBook,
  saveReadBook,
  syncReadBook,
} from "../../db";
import { toast } from "react-toastify";
import OutlinedButton from "../../md-components/OutlinedButton";
import "./AccountPage.css";
import FilledButton from "../../md-components/FilledButton";
import { useNavigate } from "react-router";

const Main = () => {
  const navigate = useNavigate();
  const [accountInfo, setAccountInfo] = useState(false);
  const [bookshelf, setBookshelf] = useState([]);

  async function loadAccount() {
    if (window.onLine) {
      axios.get("/user").then((res) => setAccountInfo(res.data));
    }
  }
  useEffect(() => {
    if (accountInfo !== false) return;
    loadAccount();
    updateBookshelf();
  }, [accountInfo]);
  async function updateBookshelf() {
    let caches = await window.caches.open("bookCovers");
    let reader = await getAllReadBooks();
    if (bookshelf.length !== 0) return;
    reader
      .filter((book) => book.onBookshelf)
      .map(async (value) => {
        let newBook;
        if (value.offline === undefined) {
          let localBook = await getBook(value.id);
          if (localBook !== undefined) {
            await saveReadBook(value.id, true);
          } else {
            await saveReadBook(value.id, false);
          }
        }
        if (window.onLine) {
          if (
            (await caches.match(`/api/book/${value.id}/cover`)) === undefined
          ) {
            await caches.add(`/api/book/${value.id}/cover`);
          }
        }
        if (value.bookInfo === undefined) {
          if (window.onLine) {
            let bookInfo = (await axios.get("/book/" + value.id)).data;
            await putReadBook(value.id, true, bookInfo);
            newBook = (
              <BookCard
                key={value.id}
                id={value.id}
                authors={bookInfo.authors}
                title={bookInfo.title}
                reader={true}
                offline={value.offline}
              />
            );
          } else {
            newBook = (
              <BookCard
                key={value.id}
                id={value.id}
                authors={[]}
                title={"Подключитесь к интернету"}
                reader={true}
                offline={false}
              />
            );
          }
        } else {
          newBook = (
            <BookCard
              key={value.id}
              id={value.id}
              authors={value.bookInfo.authors}
              title={value.bookInfo.title}
              reader={true}
              offline={value.offline}
            />
          );
        }
        setBookshelf((prev) => [...prev, newBook]);
      });
  }
  return (
    <>
      {/* <IconButton onClick={() => {
            setAccountInfo(false)
        }}><Icon>refresh</Icon></IconButton> */}
      {window.onLine ? (
        <h2>Здравствуйте, {accountInfo.name || <Skeleton width={150} />}</h2>
      ) : (
        <h2>
          Офлайн режим{" "}
          <Icon style={{ lineHeight: "30px", height: "100%" }}>cloud_off</Icon>
        </h2>
      )}
      <FilledButton
        className="w-26"
        //style={{"--md-filled-button-container-color": "var(--md-sys-color-error)"}}
        onClick={() => {
          document.cookie = "token=;expires=Thu, 01 Jan 1970 00:00:00 GMT";
          navigate("/login");
        }}
      >
        выйти
      </FilledButton>
      {/* <h3>Синхронизация</h3>
      <div className="account_buttons_container">
        <OutlinedButton
          className="account_action_button"
          disabled={!window.onLine}
          onClick={async () => {
            axios.put("/user/reader", await getAllReadBooks()).then((res) => {
              if (res.status === 200) {
                toast.success("Успешно!");
              } else {
                toast.error("Что то пошло не так");
              }
            });
          }}
        >
          <Icon slot="icon">upload</Icon>
          Загрузить на сервер
        </OutlinedButton>
        <OutlinedButton
          className="account_action_button"
          disabled={!window.onLine}
          onClick={async () => {
            axios.get("/user/reader").then(async (res) => {
              if (res.status === 200) {
                await window.caches.delete("bookCovers");
                await syncReadBook(res.data);
                updateBookshelf();
                toast.success("Успешно!");
              } else {
                toast.error("Что то пошло не так");
              }
            });
          }}
        >
          <Icon slot="icon">download</Icon>
          Получить с сервера
        </OutlinedButton>
      </div> */}
      {/*<h3>Избранное</h3>
        <div className="results_container">
            {
                window.ononline ?
                    accountInfo.favorites === undefined ?
                    <Skeleton/>
                    :
                    accountInfo.favorites === null || accountInfo.favorites.length === 0 ?
                        <p>Нет избранных книг 💔</p>
                        :
                        accountInfo.favorites.map(value => <BookCard
                            key={value.id}
                            id={value.id}
                            authors={value.authors}
                            title={value.title}
                        />)
                : <p>Невозможно загрузить избранное в офлайн режиме ✈️</p>
            }
        </div>*/}
      {/* todo */}
      {/* <h3>Продолжить чтение</h3>
        <div className="results_container">
            {
                bookshelf === false ?
                <Skeleton/>
                :
                bookshelf.length === 0 ?
                    <p>Вы еще ничего не добавляли на полку</p>
                    :
                    bookshelf
            }
        </div> */}
    </>
  );
};

export default Main;
