import React, { Component } from 'react';
import PropTypes from 'prop-types';
import Moment from 'moment';
import {
	Feed as SemanticFeed,
	Icon as SemanticIcon,
	Tab as SemanticTab
} from 'semantic-ui-react';
import Marked from '../Marked';

import * as styles from './Style.less';

export default class SidebarNotifications extends Component {
	static propTypes = {
		data: PropTypes.array.isRequired,
		onDismiss: PropTypes.func.isRequired
	};

	state = {
		data: this.props.data
	};

	componentWillReceiveProps(nextProps) {
		this.setState({
			data: nextProps.data
		});
	}

	onDismiss(id) {
		this.setState(prevState => ({
			data: prevState.data.map((row) => {
				if (row.id === id) {
					return Object.assign(row, { dismissed: true });
				}

				return row;
			})
		}), this.props.onDismiss(id));
	}

	render() {
		return (
			<div
				className={styles.SidebarNotifications}
			>
				<SemanticTab
					renderActiveOnly={false}
					activeIndex={this.state.index}
					menu={{
						secondary: true,
						pointing: true,
						attached: false
					}}
					onTabChange={(e, data) => {
						this.setState({
							index: data.activeIndex
						});
					}}
					panes={[
						{
							menuItem: 'Notifications',
							pane: (
								<SemanticTab.Pane
									key="Notifications"
									className={styles.Notifications}
								>
									<SemanticFeed className={styles.List}>
										{
											this.state.data.filter(n => !n.dismissed).length > 0 ? (
												this.state.data.filter(n => !n.dismissed).map((notification) => {
													return (
														<SemanticFeed.Event
															key={notification.id}
															className={`${styles.Notification} ${notification.read ? 'read' : 'unread'}`}
														>
															<SemanticFeed.Content>
																<SemanticFeed.Summary>
																	<h5>
																		{notification.title}
																	</h5>
																	<SemanticIcon
																		name="times circle"
																		onClick={() => this.onDismiss(notification.id)}
																	/>
																	<SemanticFeed.Date>{Moment(notification.timestamp).fromNow()}</SemanticFeed.Date>
																</SemanticFeed.Summary>
																<SemanticFeed.Extra text>
																	{Marked.display(notification.content)}
																</SemanticFeed.Extra>
															</SemanticFeed.Content>
														</SemanticFeed.Event>
													);
												})
											) : (
												<div className={styles.Empty}>
													You&apos;re all caught up
												</div>
											)
										}
									</SemanticFeed>
								</SemanticTab.Pane>
							)
						}
					]}
				/>
			</div>
		);
	}
}
