import React, { Component } from 'react';
import PropTypes from 'prop-types';
import { createClient } from 'contentful';
import {
	Dropdown as SemanticDropdown,
	Image as SemanticImage,
	Modal as SemanticModal,
	Tab as SemanticTab
} from 'semantic-ui-react';
import Container from '../Container';
import Loader from '../Loader';
import Marked from '../Marked';
import Numbro from '../Numbro';

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

export default class SidebarDocs extends Component {
	static propTypes = {
		visible: PropTypes.bool
	};

	static defaultProps = {
		visible: false
	};

	static openSignal(signal) {
		this.setState({
			signal
		}, () => {
			localStorage.setItem('docs-glossary', signal);
		});
	}

	static openImage(href) {
		this.setState({
			modal: (
				<SemanticModal
					open
					basic
					onClose={() => {
						this.setState({ modal: null });
					}}
					className={styles.Modal}
				>
					<SemanticModal.Content>
						<SemanticImage
							src={href}
							className={styles.ModalImage}
						/>
					</SemanticModal.Content>
				</SemanticModal>
			)
		});
	}

	constructor(props) {
		super(props);

		SidebarDocs.openSignal = SidebarDocs.openSignal.bind(this);
		SidebarDocs.openImage = SidebarDocs.openImage.bind(this);

		window.PP_Sidebar_OpenSignal = SidebarDocs.openSignal;
		window.PP_Sidebar_OpenImage = SidebarDocs.openImage;

		this.state = {
			fetchedEntries: false,
			signal: localStorage.getItem('docs-glossary') || null,
			signals: {},
			modal: null
		};

		if (global.test) {
			// Internal users get Preview API
			this.Contentful = createClient({
				space: 'mg298b52kz6q',
				accessToken: '682342e53a26811c1af151d4d33e8b3549d3a5986e84326c5d6781bb25a2ed12',
				host: 'preview.contentful.com'
			});
		} else {
			// External users get Published API
			this.Contentful = createClient({
				space: 'mg298b52kz6q',
				accessToken: '4b23e7321009c7aff939e9043ca2322b01534fa7bde040270146abfd26dc4bc3'
			});
		}
	}

	componentWillReceiveProps(nextProps) {
		if (nextProps.visible && !this.state.fetchedEntries) {
			this.fetchEntries();
		}
	}

	fetchEntries() {
		this.setState({ fetchedEntries: true });

		this.Contentful.getEntries({
			content_type: 'signal',
			'fields.glossary': true,
			select: 'fields.name,fields.label,fields.description,fields.rangeLow,fields.rangeHigh,fields.insight,fields.format',
			order: 'fields.label'
		})
			.then((response) => {
				const signals = {};

				response.items.forEach((row) => {
					signals[row.fields.name] = { ...row.fields, id: row.sys.id };
				});

				this.setState(prevState => ({
					signal: prevState.signal ? prevState.signal : response.items[0].fields.name,
					signals
				}));
			});
	}

	render() {
		const {
			signals
		} = this.state;

		const signal = signals[this.state.signal];

		return (
			<div
				className={styles.SidebarDocs}
			>
				<SemanticTab
					renderActiveOnly={false}
					activeIndex={0}
					menu={{
						secondary: true,
						pointing: true,
						attached: false
					}}
					panes={[
						{
							menuItem: 'Signal Glossary',
							pane: (
								<SemanticTab.Pane
									key="Glossary"
									className={styles.Glossary}
								>
									{
										(signal && signals) ? (
											<Container className={styles.Signal}>
												<SemanticDropdown
													ref={(element) => { this.dropdownGlossary = element; }}
													scrolling
													pointing="top left"
													search
													selectOnNavigation={false}
													selectOnBlur={false}
													options={Object.keys(signals).map(s => ({
														text: signals[s].label,
														value: signals[s].name
													}))}
													value={signal.name}
													onChange={(e, { value }) => {
														SidebarDocs.openSignal(value);

														// override SUIs stupid selection logic
														const index = Object.keys(signals).findIndex(s => signals[s].name === value) || 0;
														this.dropdownGlossary.setState({ selectedIndex: index });
													}}
												/>
												<p>
													{signal.description}
												</p>
												{
													(signal.rangeLow && signal.rangeHigh) && (
														<>
															<h5 className={styles.Heading}>
																Target Range
															</h5>

															<p>
																{Numbro.format(signal.rangeLow, signal.format)} to {Numbro.format(signal.rangeHigh, signal.format)}
															</p>
														</>
													)
												}
												{
													signal.insight && (
														<>
															<h5 className={styles.Heading}>
																Insights
															</h5>

															{Marked.display(signal.insight)}
														</>
													)
												}
											</Container>
										) : (
											<Loader minimal />
										)
									}
								</SemanticTab.Pane>
							)
						}
					]}
				/>
				{this.state.modal}
			</div>
		);
	}
}
