import { ProductCards } from "./components";
import { useEffect, useState } from "react";
import type { Product, ProductLine } from "../../types";
import Order from "./components/order/Order";
import styles from "./Catalog.module.css";


const Catalog = () => {
  const [products, setProducts] = useState<Product[]>([]);
  const [productLines, setProductLines] = useState<ProductLine[] | []>([]);

  useEffect(() => {
    async function fetchProducts(){
      try{
        const response = await fetch("http://localhost:8010/api/v1/products");
        const data = await response.json();
        setProducts(data);
      }catch(error){
        console.error(`Este es el error: ${error}`);
      };
    };
    fetchProducts();
  }, []);

  function addProductLine(product: Product, quantity: number){
    const newProductLine: ProductLine = {
      id: Date.now(),
      product: product,
      quantity: quantity,
      unitPrice: product.price,
      totalAmount: quantity * product.price,
    };

    setProductLines([...productLines, newProductLine]);
  }

  return (
    <div className={styles.layout}>
      <section className={styles.catalog}>
        <ProductCards products={products} addProductLine={addProductLine}/>
      </section>
      <aside className={styles.order}>
        <Order productLines={productLines}/>
      </aside>
    </div>
  )
}

export default Catalog;
