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

import List from "@mui/material/List";
import ListItem from "@mui/material/ListItem";
import ListItemButton from "@mui/material/ListItemButton";
import ListItemText from "@mui/material/ListItemText";
import Typography from "@mui/material/Typography";
import Paper from "@mui/material/Paper";

function Machines({ machines, onSelect }) {
    const [selectedId, setSelectedId] = useState(null);

    const handleOnClick = (machineName, machineId) => {
        onSelect(machineName, machineId);
        setSelectedId(machineId);
    };

    const machineItems = machines.map((machine) => {
        return (
            <ListItem key={machine.id} disablePadding>
                <ListItemButton
                    selected={selectedId === machine.id}
                    onClick={(event) => handleOnClick(machine.name, machine.id)}
                >
                    <ListItemText primary={machine.name} />
                </ListItemButton>
            </ListItem>
        );
    });

    return (
        <>
            <Typography variant="h4" gutterBottom>
                Machines
            </Typography>

            <List>
                <Paper>{machineItems}</Paper>
            </List>
        </>
    );
}

export { Machines };
