import TodoListEntry from "./TodoListEntry.jsx";
import { CircularProgress } from '@rmwc/circular-progress';
import { fetchTodos } from "../../actions.js";
import { connect } from "react-redux";
import React, { useEffect } from "react";
import { Fab } from "@rmwc/fab";
import { Link } from "react-router-dom";

const TodoList = ({ handleFetchTodos, todos }) => {
	useEffect(() => {
		handleFetchTodos();
	}, [ handleFetchTodos ]);

	const RenderTodoListEntry = ({ renderTodos }) => {
		if (renderTodos.isLoading) {
			return <div className="message"><CircularProgress size="xlarge"/></div>;
		}
		else if (renderTodos.entries === null || renderTodos.entries.length === 0){
			 return <div className="message"><p>Noch keine Einträge</p></div>;
		}
		return renderTodos.entries.map(t => <TodoListEntry key = {t.listId} todo = {t}/>);
	};

	return (
		<div>
			<div className="list-block">
				<RenderTodoListEntry  renderTodos={todos}/>
			</div>
			<Link to="/todoList/new">
				<Fab icon="add" className="addButton"/>
			</Link>
		</div>
	);
};

export default connect(
	(state, ownProps) => {
		const { todos } = state;
		return Object.assign({}, { todos: todos }, ownProps);
	},
	(dispatch) => {
		return { handleFetchTodos: () => dispatch(fetchTodos()) };
	}
)(TodoList);