import {useState} from 'react';
import {useRecoilState, useRecoilValue} from 'recoil';
import {jwtToken} from '../../recoilState/usersState';
import {Link, useHistory, useParams} from 'react-router-dom';
import {robotById} from '../../recoilState/robotsState';
import {Button, Container, Form, Row, Col} from 'react-bootstrap';
import {createRobot, updateRobot} from '../../api/robotsAPI';
import {manufacturersState} from '../../recoilState/manufacturersState';
import {categoriesState} from '../../recoilState/categoriesState';

const RobotForm = (props) => {
    const {id} = useParams();
    const jwt = useRecoilValue(jwtToken);
    const [robot, setRobot] = useRecoilState(robotById(id));
    const manufacturers = useRecoilValue(manufacturersState);
    const categories = useRecoilValue(categoriesState);
    const [name, setName] = useState(robot ? robot.name : '');
    const [serialNumber, setSerialNumber] = useState(robot ? robot.serialNumber : '');
    const [manufacturerId, setManufacturerId] = useState(robot ? robot.manufacturerId : undefined);
    const [categoryId, setCategoryId] = useState(robot ? robot.categoryId : undefined);
    const history = useHistory();

    const saveChanges = async (evt) => {
        evt.preventDefault();
        let newRobot = {
            ...robot,
            manufacturerId,
            name,
            serialNumber,
            categoryId
        };

        if (id) {
            await updateRobot(jwt, newRobot);
            newRobot = {
                ...newRobot,
                manufacturer: manufacturers.find(m => m.id === manufacturerId),
                category: categories.find(c => c.id === categoryId)
            }
        } else {
            newRobot = await createRobot(jwt, newRobot);
        }
        setRobot(newRobot);
        history.goBack();
    }

    if (!jwt) {
        return <Container>
            <h3>Please log in</h3>
            <p>You must be&nbsp;
                <Link to={"/login"}>logged in</Link> order to edit, create or delete a robot.</p>
        </Container>
    }

    return (
        <Container>
            <Row>
                <Col>
                    <h3>{id ? 'Edit' : 'Create'} Robot</h3>
                </Col>
            </Row>
            <Row>
                <Col>
                    <Form>
                        <Form.Group className={"my-2"}>
                            <Form.Control type="text" placeholder="Name" value={name}
                                          onChange={evt => setName(evt.target.value)}/>
                        </Form.Group>

                        <Form.Group className={"my-2"}>
                            <Form.Control type="text" placeholder="Serialnumber" value={serialNumber}
                                          onChange={evt => setSerialNumber(evt.target.value)}/>
                        </Form.Group>
                        <Form.Group className={"my-2"}>
                            <Form.Control as="select" value={manufacturerId}
                                          onChange={evt => setManufacturerId(Number(evt.target.value))}>
                                {manufacturers.map(m => <option key={m.id} value={m.id}>{m.name}</option>)}
                            </Form.Control>
                        </Form.Group>
                        <Form.Group className={"my-2"}>
                            <Form.Control as="select" value={categoryId}
                                          onChange={evt => setCategoryId(Number(evt.target.value))}>
                                {categories.map((m, i) =>
                                    <option key={i} value={m.id}>{m.name}</option>)}
                            </Form.Control>
                        </Form.Group>
                        <Form.Group className={"my-2 d-grid"}>
                            <Button variant="primary" type="submit" onClick={saveChanges}>
                                Save
                            </Button>
                        </Form.Group>

                    </Form>
                </Col>
            </Row>
        </Container>

    )
}

export default RobotForm;
