import {Button, Col, Container, Form, Row} from 'react-bootstrap';
import {Link, useHistory, useParams} from 'react-router-dom';
import {useRecoilState, useRecoilValue} from 'recoil';
import {categoryById} from '../../recoilState/categoriesState';
import {useState} from 'react';
import {createCategory, updateCategory} from '../../api/categoriesAPI';
import {jwtToken} from '../../recoilState/usersState';


const CategoryForm = () =>  {
    const {id} = useParams();
    const jwt = useRecoilValue(jwtToken);
    const [category, setCategory] = useRecoilState(categoryById(id));
    const [name, setName] = useState(category ? category.name : '');
    const [comment, setComment] = useState(category ? category.comment : '');
    const history = useHistory();

    const saveCategory = async (evt) => {
        evt.preventDefault();
        let newCategory = {...category, name, comment}
        if (id) {
            const success = await updateCategory(jwt, newCategory);
            if (success) setCategory(newCategory);
        } else {
            newCategory = await createCategory(jwt, newCategory);
            if (newCategory) setCategory(newCategory);
        }
        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"} Category</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 as="textarea" rows={3} placeholder="Enter comment" value={comment}
                                          onChange={evt => setComment(evt.target.value)}/>
                        </Form.Group>

                        <Form.Group className={"d-grid my-2"}>
                            <Button variant="primary" type="submit" onClick={saveCategory}>
                                Save
                            </Button>
                        </Form.Group>
                    </Form>
                </Col>
            </Row>
        </Container>
    );

}

export default CategoryForm;
