import {Button, Row} from 'react-bootstrap';
import Category from './category';
import {useRecoilState, useRecoilValue} from 'recoil';
import {jwtToken} from '../../recoilState/usersState';
import {categoriesState} from '../../recoilState/categoriesState';
import {deleteCategory} from '../../api/categoriesAPI';
import {useHistory, useRouteMatch} from 'react-router-dom';

const CategoryList = () => {
    const [categories, setCategories] = useRecoilState(categoriesState);
    const history = useHistory();
    const match = useRouteMatch();
    const jwt = useRecoilValue(jwtToken);

    const deleteHandler = (id) => {
        const success = deleteCategory(jwt, id);
        if (success) setCategories(categories.filter(c => c.id !== id));
    }

    return <Row>
        <div className={"d-grid"}>
            <Button variant={'primary'} onClick={() => history.push(`${match.url}/form`)}>New category</Button>
        </div>

        {categories.map(c => <Category key={c.id} {...c} deleteHandler={jwt ? () => deleteHandler(c.id) : undefined}/>)}
    </Row>
}

export default CategoryList;
