import axios from "axios";
import { useEffect, useRef, useState } from "react";
import BookCard from "../../components/bookCard/BookCard";
import LinearProgress from "../../md-components/LinearProgress";
import Icon from "../../md-components/Icon";
import { Link } from "react-router-dom";
import IconButton from "../../md-components/IconButton";
import "./CollectionSlider.css";
import DefaultIconButton from "../../md-components/DefaultIconButton";

const CollectionSlider = ({ id, name, onDelete }) => {
  const [collectionInfo, setCollectionInfo] = useState(false);
  const [collectionBooks, setCollectionBooks] = useState(false);
  const [curPage, setCurPage] = useState(0);
  const scrollRef = useRef();

  const loadCollectionInfo = () => {
    setCollectionInfo(false);
    axios.get("/collection/" + id).then((res) => setCollectionInfo(res.data));
    axios
      .get("/search", { params: { collection: id, offset: 0, limit: 9 } })
      .then((res) => setCollectionBooks(res.data.books));
  };

  useEffect(() => loadCollectionInfo(), [id]);

  // до лучших времен
  // useEffect(() => {
  //     if (scrollRef.current !== undefined) {
  //         console.log('add listener')
  //         scrollRef.current.addEventListener("scroll", e => console.log(e.target.scrollLeft))
  //     }
  // }, [scrollRef])

  useEffect(() => {
    if (scrollRef.current == undefined) return;
    scrollRef.current.scrollLeft = 205 * 4 * curPage;
  }, [curPage]);
  if (!collectionInfo || !collectionBooks) {
    return (
      <>
        <br />
        <LinearProgress indeterminate style={{ width: "100%" }} />
      </>
    );
  }
  const userInfo = JSON.parse(localStorage.getItem("userInfo"));
  return (
    <>
      <div style={{ display: "inline-flex", alignItems: "center", gap: 10 }}>
        <DefaultIconButton
          onClick={() => onDelete(collectionInfo.creator.id === userInfo.id)}
        >
          <Icon>
            {collectionInfo.creator.id === userInfo.id
              ? "delete"
              : "bookmark_remove"}
          </Icon>
        </DefaultIconButton>
        <Link to={"/collection/" + id} style={{ textDecoration: "none" }}>
          <h3 style={{ display: "flex", width: "fit-content" }}>
            {name}
            <Icon>chevron_right</Icon>
          </h3>
        </Link>
      </div>
      <div
        style={{
          position: "relative",
          width: "fit-content",
        }}
      >
        <IconButton
          className="slider_button"
          onClick={() => setCurPage((p) => p - 1)}
          style={{
            left: -15,
            top: 135,
            opacity: curPage === 0 ? 0 : 1,
            transition: "all 0.2s",
          }}
          disabled={curPage === 0}
        >
          <Icon>chevron_left</Icon>
        </IconButton>
        {collectionBooks.length === 0 ? (
          <span style={{ marginLeft: 25 }}>
            добавьте первую книгу в коллекцию
          </span>
        ) : (
          <></>
        )}
        <div
          ref={scrollRef}
          style={{
            translate: "all 1s",
            scrollBehavior: "smooth",
          }}
          className="scroll_container"
        >
          <div
            style={{
              display: "flex",
              gap: 5,
              width:
                collectionBooks.length > 8
                  ? 205 * 8
                  : 205 * collectionBooks.length,
            }}
          >
            {collectionBooks.slice(0, 7).map((book) => (
              <BookCard
                key={book.id}
                id={book.id}
                title={book.title}
                authors={book.authors}
                collectionDelId={id}
                fixed
                filetype={book.filetype}
              />
            ))}
            {collectionBooks.length > 8 ? (
              <Link to={"/collection/" + id} style={{ textDecoration: "none" }}>
                <div
                  style={{
                    display: "flex",
                    alignItems: "center",
                    justifyContent: "center",
                    height: 280,
                    width: 180,
                    margin: 10,
                    borderRadius: 12,
                    background: "var(--md-sys-color-primary-container)",
                    color: "var(--md-sys-color-on-primary-container)",
                    position: "relative",
                    userSelect: "none",
                  }}
                >
                  <md-ripple />
                  <span>Еще</span>
                  <Icon>chevron_right</Icon>
                </div>
              </Link>
            ) : (
              <></>
            )}
          </div>
        </div>
        <IconButton
          className="slider_button"
          onClick={() => setCurPage((p) => p + 1)}
          style={{
            right: -15,
            top: 135,
            opacity: (curPage === 0) & (collectionBooks.length > 4) ? 1 : 0,
            transition: "all 0.2s",
          }}
          disabled={(curPage !== 0) | (collectionBooks.length < 4)}
        >
          <Icon>chevron_right</Icon>
        </IconButton>
      </div>
    </>
  );
};

export default CollectionSlider;
