import type { Product } from "@/services/models/Product";

import CartItem from "@/components/CartItem/CartItem";
import EmptyCart from "@/components/EmptyCart/EmptyCart";

import { getCart } from "@/services/db/cartAPI";
import { getProductById } from "@/services/db/productsAPI";

import type { Cart, PopulatedCart } from "@/services/models/Cart";
import CartSummaryItem from "../CartSummaryItem/CartSummaryItem";
import styles from "./CartTable.module.scss";

export default async function CartTable() {
  const cart = await getCart();

  return (
    <div className={styles["cart-table"]}>
      <span className={styles["cart-table__heading"]}>
        Моя Корзина ({cart?.items.length ?? 0} штук)
      </span>

      {cart?.items ? (
        <table className={styles["cart-table__table"]}>
          <thead>
            <tr>
              <th>Продукт</th>
              <th>Цена за Штуку</th>
              <th>Количество</th>
              <th>Сумма</th>
            </tr>
          </thead>

          <tbody>
            {cart.items.map(async (item) => {
              const product = await getProductById(item.productId);

              return (
                <CartItem
                  key={item.sku}
                  item={
                    JSON.parse(JSON.stringify(item)) as Cart["items"][number]
                  }
                  product={JSON.parse(JSON.stringify(product)) as Product}
                />
              );
            })}
          </tbody>
        </table>
      ) : (
        <EmptyCart />
      )}

      <div className={styles["cart-table__cards"]}>
        {cart?.items.map((item) => (
          <CartSummaryItem
            key={item.sku}
            item={
              JSON.parse(JSON.stringify(item)) as PopulatedCart["items"][number]
            }
            type="table"
          />
        ))}
      </div>
    </div>
  );
}
