import * as React from "react";
import { useState, useEffect } from "react";

import Grid from "@mui/material/Unstable_Grid2";

import { machinesApi } from "../api";
import { Machines } from "../components/Machines";
import { Products } from "../components/Products";

function Home() {
    const [machines, setMachines] = useState([]);
    const [productsData, setProductsData] = useState(null);

    useEffect(() => {
        machinesApi.list().then((response) => {
            setMachines(response.data.machines);
        });
    }, []);

    const onMachineSelect = (machineName, machineId) => {
        machinesApi.listProducts(machineId).then((response) => {
            setProductsData({
                machineName,
                products: response.data.products,
            });
        });
    };

    return (
        <Grid container spacing={2}>
            <Grid md={3}>
                <Machines machines={machines} onSelect={onMachineSelect} />
            </Grid>
            <Grid md={9}>
                {productsData && <Products machineName={productsData.machineName} products={productsData.products} />}
            </Grid>
        </Grid>
    );
}

export { Home };
