import {useRecoilState, useRecoilValue} from 'recoil';
import Manufacturer from './manufacturer';
import {Row, Col, Button} from 'react-bootstrap';
import {manufacturersState} from '../../recoilState/manufacturersState';
import {jwtToken} from '../../recoilState/usersState';
import {deleteManufacturer} from '../../api/manufacturersAPI';
import React from 'react';
import {useHistory, useRouteMatch} from 'react-router-dom';

const ManufacturerList = () => {
    const [manufacturers, setManufacturers] = useRecoilState(manufacturersState);
    const jwt = useRecoilValue(jwtToken);
    const history = useHistory();
    const match = useRouteMatch();

    const deleteManufacturerHandler = async (id) => {
        const success = await deleteManufacturer(jwt, id);
        if (success) setManufacturers(manufacturers.filter(m => m.id !== id));
    }

    return <Row>
        <h3>All manufacturers</h3>
        <div className={"d-grid"}>
            <Button variant={'primary'} onClick={() => history.push(`${match.url}/form`)}>New manufacturer</Button>
        </div>
        {manufacturers.map(m =>
            <Col xs={12} key={m.id}>
                <Manufacturer {...m} deleteHandler={() => deleteManufacturerHandler(m.id)}/>
            </Col>
        )}
    </Row>
}

export default ManufacturerList;
