import {useContext} from 'react';
import {ViewContext} from '../app';
import {addProductToBasket} from '../API/shoppingBasketAPI';
import {useHistory, useRouteMatch} from 'react-router-dom';
import {shoppingBasket} from '../recoilState/basketState';
import {useSetRecoilState} from 'recoil';

const Repository = ({id, name, price, reviews, shortDescription, deleteProductHandler}) => {
    const {adminView} = useContext(ViewContext);
    const history = useHistory();
    const match = useRouteMatch();
    const setBasket = useSetRecoilState(shoppingBasket);
    const totalRating = Math.round(reviews
        .map(r => r.rating)
        .reduce((prev, curr) => prev + curr, 0) / reviews.length)

    const addProductToBasketHandler = () => {
       addProductToBasket(id, name, price).then((b) => setBasket(b));
    }

    return <div className="product">
        <h2>{name} - {totalRating}/5</h2>
        <p>{shortDescription}</p>

        {adminView ?
            <div>
                <button onClick={() => history.push(`${match.path}/${id}`)}>Edit</button>
                <button onClick={deleteProductHandler}>Delete</button>
            </div> :
            <div>
                <button onClick={() => history.push(`${match.path}/${id}`)}>Details</button>
                <button onClick={addProductToBasketHandler}>Add to basket</button>
            </div>
        }

    </div>
}

export default Repository;
