"use client";

import type { Cart, PopulatedCart } from "@/services/models/Cart";
import type { Category } from "@/services/models/Category";
import type { Collection } from "@/services/models/Collection";
import type { PopulatedProduct } from "@/services/models/Product";
import type { Params } from "next/dist/server/request/params";

import ChevronLeftSVG from "@/assets/icons/chevron-left.svg";
import ChevronRightSVG from "@/assets/icons/chevron-right.svg";

import FilterButton from "@/components/FilterButton/FilterButton";
import ProductCard from "@/components/ProductCard/ProductCard";
import ProductListSort from "@/components/ProductListSort/ProductListSort";

import { useMediaQuery } from "@/hooks/useMediaQuery";
import { useState } from "react";
import Button from "../Button/Button";
import EmptyResults from "../EmptyResults/EmptyResults";
import styles from "./ProductCardList.module.scss";

export default function ProductCardList({
  params,
  products,
  categories,
  collections,
  cart,
}: {
  params: Params;
  products: PopulatedProduct[];
  categories: Category[];
  collections: Collection[];
  cart: PopulatedCart;
}) {
  const [page, setPage] = useState(1);

  const isMobile = useMediaQuery("max-width", "products-one-column");
  const pageSize = isMobile ? 5 : 15;
  const isPaginated = Math.ceil(products.length / pageSize) > 1;

  const currentCategory = categories.find(
    (category) => category.slug === params["category"],
  );
  const currentCollection = collections.find(
    (collection) => collection.slug === params["collection"],
  );

  const displayedProducts = isPaginated
    ? products.slice((page - 1) * pageSize, page * pageSize)
    : products;
  const heading =
    currentCategory && currentCollection
      ? `${currentCategory.name} ~ ${currentCollection.name}`
      : (currentCategory?.name ?? currentCollection?.name ?? "Каталог");

  function handleNextPage() {
    if (page + 1 > Math.ceil(products.length / pageSize)) return;

    setPage((page) => page + 1);

    window.scrollTo({ top: 0 });
  }

  function handlePreviousPage() {
    if (page - 1 < 1) return;

    setPage((page) => page - 1);

    window.scrollTo({ top: 0 });
  }

  return (
    <div className={styles["product-card-list"]}>
      <div className={styles["product-card-list__header"]}>
        <span className={styles["product-card-list__heading"]}>{heading}</span>

        <div className={styles["product-card-list__button-group"]}>
          <ProductListSort />

          <FilterButton
            className={styles["product-card-list__filter-button"]}
          />
        </div>
      </div>

      {displayedProducts.length > 0 ? (
        <ul className={styles["product-card-list__list"]}>
          {displayedProducts.map((product) => (
            <ProductCard
              key={product._id.toString()}
              product={JSON.parse(JSON.stringify(product)) as PopulatedProduct}
              cart={JSON.parse(JSON.stringify(cart)) as Cart | null}
            />
          ))}
        </ul>
      ) : (
        <EmptyResults />
      )}

      {isPaginated && (
        <div className={styles["product-card-list__paginator"]}>
          <Button
            icon={ChevronLeftSVG}
            variant="primary"
            onClick={handlePreviousPage}
          />

          <span className={styles["product-card-list__page"]}>{page}</span>

          <Button
            icon={ChevronRightSVG}
            variant="primary"
            onClick={handleNextPage}
          />
        </div>
      )}
    </div>
  );
}
