import axios from "axios";
import { useEffect, useState } from "react";
import BookCard from "./bookCard/BookCard";
import LinearProgress from "../md-components/LinearProgress";
import IconButton from "../md-components/IconButton";
import Icon from "../md-components/Icon";

const Pagination = ({ offset, setOffset, perPage, total }) => {
  return (
    <div
      style={{
        display: "flex",
        alignItems: "center",
        gap: "10px",
        width: "100%",
        justifyContent: "center",
      }}
    >
      <IconButton
        disabled={offset - perPage < 0}
        onClick={() => setOffset((prev) => prev - perPage)}
      >
        <Icon>arrow_back</Icon>
      </IconButton>
      <span>
        {total > 0 ? offset + 1 : 0}-
        {offset + perPage > total ? total : offset + perPage}
        {" из " /* если убрать ковычки - не будет пробеловё*/}
        {total}
      </span>
      <IconButton
        disabled={offset + perPage + 1 > total}
        onClick={() => setOffset((prev) => prev + perPage)}
      >
        <Icon>arrow_forward</Icon>
      </IconButton>
    </div>
  );
};

const SearchResults = ({ query, author, collection }) => {
  const [searchResults, setSearchResults] = useState(false);
  const [offset, setOffset] = useState(0);
  useEffect(() => {
    setSearchResults(false);
    axios
      .get("/search", {
        params: {
          q: query,
          author: author,
          collection: collection,
          offset: offset,
          limit: 8,
        },
      })
      .then((res) => setSearchResults(res.data));
  }, [offset]);
  if (!searchResults) {
    return <LinearProgress indeterminate style={{ width: "100%" }} />;
  }
  if (searchResults.count === 0) {
    return <p style={{ marginLeft: 20 }}>ничего не найдено</p>;
  }
  return (
    <>
      <div className="results_container">
        {searchResults.books.map((book) => (
          <BookCard
            key={book.id}
            id={book.id}
            title={book.title}
            authors={book.authors}
            filetype={book.filetype}
          />
        ))}
      </div>
      <Pagination
        offset={offset}
        setOffset={setOffset}
        perPage={10}
        total={searchResults.count}
      />
    </>
  );
};

export default SearchResults;
