import {useHistory, useRouteMatch} from 'react-router-dom';
import {Button, Row} from 'react-bootstrap';
import {useRecoilState, useRecoilValue} from 'recoil';
import {robotsState} from '../../recoilState/robotsState';
import Robot from './robot';
import Col from 'react-bootstrap/Col';
import React from 'react';
import {jwtToken} from '../../recoilState/usersState';
import {deleteRobot} from '../../api/robotsAPI';

const RobotList = () => {
    const history = useHistory();
    const match = useRouteMatch();
    const [robots, setRobots] = useRecoilState(robotsState);
    const jwt = useRecoilValue(jwtToken);

    const deleteRobotHandler = async (id) => {
        const success = await deleteRobot(jwt, id);
        if (success) setRobots(robots.filter(r => r.id !== id));
    }

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

        {robots.map(r =>
            <Col xs={12} key={r.id}>
                <Robot {...r} deleteHandler={jwt ? () => deleteRobotHandler(r.id) : undefined}/>
            </Col>
        )}
    </Row>
}

export default RobotList;
