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

const ItemsApp = () => {
    const usePersistedState = (key, initialValue) => {
        const [data, setData] = useState(initialValue);

        useEffect(() => {
            const savedData = JSON.parse(localStorage.getItem(key));
            if (savedData) {
                setData(savedData);
            }
        }, []);
    
        useEffect(() => {
            localStorage.setItem(key, JSON.stringify(data));
        }, [data]);

        return [data, setData];

    };
    
    const [items, setItems] = usePersistedState( 'items', []);


    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;