import * as React from "react";
import Grid from "@mui/material/Unstable_Grid2";
import Typography from "@mui/material/Typography";
import { ProductCard } from "./ProductCard";
import { ProductModal } from "./ProductModal";
import { productsApi } from "../api";

function Products({ machineName, products, onSelect }) {
    const [productModal, setProductModal] = React.useState({ isOpen: false, product: null });

    const onProductSelect = (productId) => {
        productsApi.get(productId).then((response) => {
            setProductModal({
                isOpen: true,
                product: response.data,
            });
        });
    };

    const onProductModalClose = () => {
        setProductModal({
            isOpen: false,
            productId: null,
        });
    };

    const productItems = products.map((product) => {
        return (
            <Grid md={6} key={product.id} sx={{ display: "flex" }}>
                <ProductCard product={product} onClick={onProductSelect} />
            </Grid>
        );
    });

    return (
        <>
            <Typography variant="h4" gutterBottom>
                Products - {machineName}
            </Typography>

            <Grid container spacing={2}>
                {productItems}
            </Grid>

            {productModal.isOpen && <ProductModal product={productModal.product} onClose={onProductModalClose} />}
        </>
    );
}

export { Products };
