import { useNavigate, useSearchParams } from "react-router-dom";
import BookCard from "../components/bookCard/BookCard";
import { useEffect, useState } from "react";
import "@material/web/progress/linear-progress";
import LinearProgress from "../md-components/LinearProgress";
import "./SearchPage.css";
import axios from "axios";
import IconButton from "../md-components/IconButton";
import Icon from "../md-components/Icon";

const Pagination = ({ total }) => {
  const [searchParams, setSearchParams] = useSearchParams();
  const [perPage, setPerPage] = useState(10);
  return (
    <div
      style={{
        display: "flex",
        alignItems: "center",
        gap: "10px",
        width: "100%",
        justifyContent: "center",
      }}
    >
      <IconButton
        disabled={Number(searchParams.get("offset")) - perPage < 0}
        onClick={() => {
          searchParams.set(
            "offset",
            Number(searchParams.get("offset")) - perPage
          );
          setSearchParams(searchParams);
        }}
      >
        <Icon>arrow_back</Icon>
      </IconButton>
      <span>
        {Number(searchParams.get("offset")) + 1}-
        {Number(searchParams.get("offset")) + perPage > total
          ? total
          : Number(searchParams.get("offset")) + perPage}
        {" из "}
        {total}
      </span>
      <IconButton
        disabled={Number(searchParams.get("offset")) + perPage + 1 > total}
        onClick={() => {
          searchParams.set(
            "offset",
            Number(searchParams.get("offset")) + perPage
          );
          setSearchParams(searchParams);
        }}
      >
        <Icon>arrow_forward</Icon>
      </IconButton>
    </div>
  );
};

const SearchPage = () => {
  const [searchParams, setSearchParams] = useSearchParams();
  const [result, setResult] = useState(false);
  const navigate = useNavigate();

  const loadResults = async () => {
    setResult(false);
    axios
      .get("/search", {
        params: Object.fromEntries(searchParams.entries()),
      })
      .then((res) => setResult(res.data));
  };
  useEffect(() => {
    if (!window.onLine) navigate("/offline");
    if (
      searchParams.get("offset") === null ||
      searchParams.get("limit") === null
    ) {
      searchParams.set("offset", "0");
      searchParams.set("limit", "10");
      window.history.replaceState(
        null,
        "",
        `/search?${searchParams.toString()}`
      );
      setSearchParams(searchParams);
    }
    loadResults();
  }, [searchParams]);
  if (!result) {
    return <LinearProgress />;
  }
  return (
    <>
      {
        <span>
          Найдено <b>{result.count}</b> за <b>{result.time}</b> с. 🚀
        </span>
      }
      <div className="results_container">
        {result.books === null ? (
          <p>Ничего не найдено 🙁</p>
        ) : (
          result.books.map((value) => (
            <BookCard
              key={value.id}
              id={value.id}
              authors={value.authors}
              title={value.title}
              fromSearch={searchParams.get("q")}
              filetype={value.filetype}
            />
          ))
        )}
        <Pagination total={result.count} />
      </div>
    </>
  );
};

export default SearchPage;
