import { Button } from "@rmwc/button";
import { Card } from "@rmwc/card";
import { TextField } from "@rmwc/textfield";
import { Link } from "react-router-dom";
import { connect } from "react-redux";
import { fetchTodos, updateTodo, addTodo } from "../../actions.js";
import { useHistory } from "react-router-dom";
import React, { useEffect, useState } from "react";

const TodoEdit = ({handleFetchTodos, handleUpdateTodo, handleAddTodo, match,  todo})=>{
    
    const [ id, setId ] = useState("");
    const [ name, setName ] = useState("");
    const history = useHistory();

    useEffect(() => {
		const id = match.params.id;
		if (id) {
			handleFetchTodos();
		}
	}, [ handleFetchTodos, match.params.id, history ]);

    useEffect(() => {
		if (todo) {
			setName(todo.name);
            setId(todo.listId);
		}
	}, [ todo ]);

    const onSubmit = () => {
        if(id){
            handleUpdateTodo(id,name);
            history.push("/");
        }
        else{ 
            handleAddTodo(name);
            history.push("/");
        }
	};

    const validateForm = () => {
        return name.length > 0;
    };

    return(
		<Card className="form-card">
            <div className="card-form">
                <TextField label="Name" value={name} onChange={event => setName(event.target.value)} required autoFocus={true} />
                <Button disabled={!validateForm()} label="Speichern" unelevated onClick={() => onSubmit()} />
                <Link to="/todoList" style={{ width: "100%" }}>
                    <Button style={{ width: "100%" }} label="Abbrechen" dense />
                </Link>
            </div>
		</Card>
    );
}
export default connect(
	(state, ownProps) => {
        const { match } = ownProps;
        const { todos } = state;
        if (todos.entries != null){
            return Object.assign({}, { todo: todos.entries.find(entry => entry.listId == match.params.id)}, ownProps);
        }
        return Object.assign({}, ownProps);
		
	},
    (dispatch) => {
        return { 
            handleUpdateTodo: (id, name) => dispatch(updateTodo(id, name)),
            handleAddTodo: (name) => dispatch(addTodo(name)),
            handleFetchTodos: () => dispatch(fetchTodos()) 
        };
	}
)(TodoEdit)
