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 { fetchEntries, updateEntry, addEntry } from "../../actions.js";
import { useHistory } from "react-router-dom";
import React, { useEffect, useState } from "react";

const EntryEdit = ({handleFetchEntries, handleUpdateEntries, handleAddEntries, match, entry})=>{
    
    const [ id, setId ] = useState("");
    const [ title, setTitle] = useState("");
    const [ done, setDone] = useState("");
    const [ todoListId, setTodoListId] = useState("");
    const history = useHistory();

    useEffect(() => {
        setTodoListId(match.params.listId);
		if (todoListId) {
			handleFetchEntries(todoListId);
		}
	}, [ handleFetchEntries, match.params.listId, history, todoListId ]);

    useEffect(() => {
		if (entry) {
			setTitle(entry.title);
            setId(entry.entryId);
            setDone(entry.done);
		}
	}, [ entry ]);

    const onSubmit = () => {
        if(id){
            handleUpdateEntries(id, title, todoListId);
            history.push(`/todolist/${todoListId}/entries`);
        }
        else{ 
            handleAddEntries(todoListId,title,done);
            history.push(`/todolist/${todoListId}/entries`);
        }
	};

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

    return(
		<Card className="form-card">
            <div className="card-form">
                <TextField label="Title" value={title} onChange={event => setTitle(event.target.value)} required autoFocus={true} />
                <Button disabled={!validateForm()} label="Speichern" unelevated onClick={() => onSubmit()} />
                <Link to={`/todolist/${todoListId}/entries`} style={{ width: "100%" }}>
                    <Button style={{ width: "100%" }} label="Abbrechen" dense />
                </Link>
            </div>
		</Card>
    );
}
export default connect(
	(state, ownProps) => {
        const { match } = ownProps;
        const { entries } = state;
        if (entries.entries != null){
            return Object.assign({}, { entry: entries.entries.find(entry => entry.entryId == match.params.id)}, ownProps);
        }
        return Object.assign({}, ownProps);
		
	},
    (dispatch) => {
        return { 
            handleUpdateEntries: (id, title, todoListId) => dispatch(updateEntry(id, title, todoListId)),
            handleAddEntries: (todoListId,title,done) => dispatch(addEntry(todoListId,title,done)),
            handleFetchEntries: (todoListId) => dispatch(fetchEntries(todoListId)) 
        };
	}
)(EntryEdit)
