import React, {useState} from 'react';
import ItemsList from './ItemsList';
import AddItemForm from './AddItemForm';

const ItemsApp = () => {
    const [items, setItems] = useState([]);

    const addItems = (text) => {
        setItems(items => [{
            name: text,
            cost: 1,
            quantity: 1
        }, ...items]);
    };

    const removeItem = (index) => {
        let res = items.filter((item, ind) => ind !== index);
        setItems(res);
    };

    const updateItem = (index, changes) => {
        setItems(items => items.map((item, idx) => idx !== index ? item : {...item, ...changes}));
      };

    return (
        <div>
            <ItemsList items={items} removeItem={removeItem} updateItem={updateItem}/>
            <AddItemForm addItems={addItems} />
            <h3>Coût total : { items.reduce((acc, i) => acc + i.cost * i.quantity, 0) }</h3>
        </div>
    );


}

export default ItemsApp;