import {useState} from 'react';
import {Link, useHistory, useParams} from 'react-router-dom';
import {manufacturerById} from '../../recoilState/manufacturersState';
import {useRecoilState, useRecoilValue} from 'recoil';
import {Button, Col, Container, Form, FormGroup, Row} from 'react-bootstrap';
import {createManufacturer, updateManufacturer} from '../../api/manufacturersAPI';
import {jwtToken} from '../../recoilState/usersState';

const ManufacturerForm = () => {
    const {id} = useParams();
    const [manufacturer, setManufacturer] = useRecoilState(manufacturerById(id));
    const [name, setName] = useState(manufacturer ? manufacturer.name : '');
    const [location, setLocation] = useState(manufacturer ? manufacturer.location : '');
    const jwt = useRecoilValue(jwtToken);
    const history = useHistory();

    const saveManufacturer = async (evt) => {
        evt.preventDefault();
        let newManufacturer = {
            ...manufacturer,
            name,
            location
        }

        if (id) {
            const success = await updateManufacturer(jwt, newManufacturer);
            if (success) setManufacturer(newManufacturer);
        } else {
            newManufacturer = await createManufacturer(jwt, newManufacturer);
            console.log(newManufacturer);
            if (newManufacturer) setManufacturer(newManufacturer);
        }
        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"} Manufacturer</h3>
                </Col>
            </Row>
            <Row>
                <Col>
                    <Form>
                        <Form.Group className={"my-2"}>
                            <Form.Control type="text" placeholder="Enter Name"
                                          value={name} onChange={evt => setName(evt.target.value)}/>
                        </Form.Group>

                        <Form.Group className={"my-2"}>
                            <Form.Control type="text" placeholder="Enter Locations"
                                          value={location} onChange={evt => setLocation(evt.target.value)}/>
                        </Form.Group>

                        <FormGroup className={"my-2 d-grid"}>
                            <Button variant="primary" type="submit" onClick={saveManufacturer}>
                                Save
                            </Button>
                        </FormGroup>

                    </Form>
                </Col>
            </Row>
        </Container>
    );
}

export default ManufacturerForm;
