import { List, ListItem, ListItemMeta } from '@rmwc/list';
import { CircularProgress } from '@rmwc/circular-progress';
import { Icon } from '@rmwc/icon';
import EntryListItem from "./EntryListEntry.jsx";
import { fetchEntries } from "../../actions.js";
import { connect } from "react-redux";
import React, { useEffect, useState } from "react";
import { useHistory } from "react-router-dom";
import { Fab } from "@rmwc/fab";
import { Link } from "react-router-dom";

const EntryList = ({ match, handleFetchEntries, entries }) =>  {

  const [todoListId, SetTodoListId] = useState("");
  const history = useHistory();

  useEffect(() => {
		const id = match.params.id;
		if (id) {
			handleFetchEntries(id, () => history.push("/"));
			SetTodoListId(id);
		}
	}, [ handleFetchEntries, match.params.id, history ]);


  const RenderEntryList = ({ renderEntry }) => {
		if (renderEntry.isLoading) {
			return <div className="message"><CircularProgress size="xlarge"/></div>;
		}
		else if (renderEntry.entries === null || renderEntry.entries.length === 0){
			 return <div className="message"><p>Noch keine Einträge</p></div>;
		}
		return renderEntry.entries.map(e => <EntryListItem key = {e.entriesId} entry = {e} todoListId ={todoListId}/>);
	};


  return (
  	<div>
    	<div className="list-block entry-list">
      		<List>
      			<RenderEntryList renderEntry={entries}/>
				  <ListItem>
					<ListItemMeta>
						<div>
							<Link to={`/todolist/`} className="listIcon">
								<Icon  icon="arrow_back" />
							</Link>
						</div>
					</ListItemMeta>
				</ListItem>
      		</List>
	  	</div>
	  	<Link to={`/todolist/${todoListId}/entries/new`}>
			<Fab icon="add" className="addButton"/>
	  	</Link>
    </div>
  );

};

export default connect(
	(state, ownProps) => {
		const { entries } = state;
		return Object.assign({}, { entries: entries }, ownProps);
	},
	(dispatch) => {
		return { handleFetchEntries: (id) => dispatch(fetchEntries(id)) };
	}
)(EntryList);