import axios from "axios";
import { useCallback, useEffect, useRef, useState } from "react";
import Icon from "../../md-components/Icon";
import LinearProgress from "../../md-components/LinearProgress";
import Dialog from "../../md-components/Dialog";
import FilledButton from "../../md-components/FilledButton";
import TextButton from "../../md-components/TextButton";
import TextField from "../../md-components/TextField";
import CollectionSlider from "./CollectionSlider";

const Collections = () => {
  const [currentCollectionTab, setCurrentCollectionTab] = useState(0);
  const [collectionPermDel, setCollectionPermDel] = useState(false);
  const [collectionTabs, setCollectionTabs] = useState(false);
  const [limit, setLimit] = useState(3);
  const createDialogRef = useRef();
  const deleteDialogRef = useRef();
  const newCollectionNameRef = useRef();

  const deleteAction = (indx, permDel) => {
    setCurrentCollectionTab(indx);
    setCollectionPermDel(permDel);
    deleteDialogRef.current.show();
  };
  const deleteCollection = (id) => {
    axios.delete("/collection/" + id).then(() => deleteFromList(id));
  };
  const removeCollection = (id) => {
    axios.delete("/user/collection/" + id).then(() => deleteFromList(id));
  };

  const deleteFromList = useCallback(
    (delId) =>
      setCollectionTabs((old) => old.filter((tab) => tab.id !== delId)),
    []
  );
  const addToList = (newColl) => setCollectionTabs((old) => [...old, newColl]);

  const createNewCollection = (name) => {
    axios
      .put("/collection", { name: name })
      .then((res) => addToList({ id: res.data.id, name: name }));
  };
  const loadCollectionsList = () => {
    setCollectionTabs(false);
    axios.get("/collection").then((res) => {
      setCollectionTabs(res.data);
    });
  };

  useEffect(() => loadCollectionsList(), []);

  if (!window.onLine) {
    return <span>Недоступно оффлайн</span>;
  }
  if (collectionTabs === false) {
    return <LinearProgress indeterminate style={{ width: "100%" }} />;
  }
  return (
    <>
      {collectionTabs.slice(0, limit).map((tab, i) => (
        <div className="mb-4">
          <CollectionSlider
            key={tab.id}
            id={tab.id}
            name={tab.name}
            onDelete={(permDel) => deleteAction(i, permDel)}
          />
        </div>
      ))}
      {collectionTabs.length > limit ? (
        <TextButton onClick={() => setLimit((pr) => (pr += 10))}>
          <Icon slot="icon">keyboard_arrow_down</Icon> загрузить еще
        </TextButton>
      ) : (
        <></>
      )}
      <TextButton
        onClick={() => {
          newCollectionNameRef.current.value = "";
          createDialogRef.current.show();
        }}
      >
        <Icon slot="icon">add</Icon> создать коллекцию
      </TextButton>
      <div
        style={{
          display: "flex",
          flexWrap: "wrap",
          gap: 5,
        }}
      >
        {/* {
            collectionInfo ? collectionInfo.books.map(book => <BookCard key={book.id}
                id={book.id}
                title={book.title}
                authors={book.authors}
                />) : <LinearProgress indeterminate style={{width: "100%"}}/>
        } */}
      </div>
      <Dialog ref={createDialogRef}>
        <div slot="headline">Новая коллекция</div>
        <div slot="content">
          <TextField ref={newCollectionNameRef} label="Название" required />
        </div>
        <div slot="actions">
          <TextButton onClick={() => createDialogRef.current.close()}>
            отмена
          </TextButton>
          <FilledButton
            onClick={() => {
              if (newCollectionNameRef.current.reportValidity()) {
                createNewCollection(newCollectionNameRef.current.value);
                createDialogRef.current.close();
              }
            }}
          >
            создать
          </FilledButton>
        </div>
      </Dialog>
      <Dialog ref={deleteDialogRef}>
        <div slot="headline">Удаление</div>
        <div slot="content" className="">
          <p>
            Вы потеряете весь список собранных книг в коллекции "
            <b>
              {collectionTabs[currentCollectionTab]
                ? collectionTabs[currentCollectionTab].name
                : ""}
            </b>
            " без возможности восстановления
          </p>
          <p>Уверены что хотите продолжить?</p>
        </div>
        <div slot="actions">
          <TextButton onClick={() => deleteDialogRef.current.close()}>
            отмена
          </TextButton>
          <FilledButton
            onClick={() => {
              let colId = collectionTabs[currentCollectionTab].id;
              collectionPermDel
                ? deleteCollection(colId)
                : removeCollection(colId);
              deleteDialogRef.current.close();
            }}
            //style={{"--md-filled-button-container-color": "red", "--md-filled-button-label-text-color": "white"}}
          >
            уверен
          </FilledButton>
        </div>
      </Dialog>
    </>
  );
};

export default Collections;
