import '../stylesheets/stories.scss';
import '../stylesheets/bbb/botbuilder.scss';
import { ChildProps } from 'react-apollo';

import * as React from 'react';
import classNames from 'classnames';

import BotCard, { AddBot } from '../components/botcard';
import Header from '../components/header';
export interface BotType {
	emoji_id: string;
	date_created: string;
	code: {
		language: string;
		content: string;
	};
}

import { graphql, compose } from 'react-apollo';
import gql from 'graphql-tag';
import { withRouter } from 'react-router';

export interface InputProps {
	token: string;
	location: any;
	match: any;
	deleteBot: typeof DeleteBotMutation;
	createBot: typeof NewBotMutation;
	botsQuery: typeof BotsQuery;
}

export class BotBuilderClass extends React.Component<ChildProps<InputProps, Response>, {}> {
	componentWillReceiveProps(nextProps) {
		if (this.props.location.key !== nextProps.location.key) {
			this.props.botsQuery.refetch();
		}
	}

	async deleteBot(emoji_id: string) {
		console.log('Deleting bot with emoji', emoji_id);
		await this.props.deleteBot({ emoji_id });
		await this.props.botsQuery.refetch();
	}

	renderBot(bot: BotType, index: number) {
		return <BotCard bot={bot} key={index} deleteBot={() => this.deleteBot(bot.emoji_id)} />;
	}

	myBots() {
		const { botsQuery } = this.props;
		if (botsQuery.isLoading) {
			return null;
		}
		if (botsQuery.viewer && botsQuery.viewer.bots_created) {
			return this.props.botsQuery.viewer.bots_created;
		} else {
			return [];
		}
	}

	async newBot(name: string) {
		await this.props.createBot({
			variables: { name }
		});
		await this.props.botsQuery.refetch();
	}

	render() {
		const { match } = this.props;
		const isLoading = !!this.props.botsQuery.loading;
		const myBots = this.myBots();
		const description = isLoading || !myBots ? 'Loading your bots' : `You have ${myBots.length} bots to play with.`;
		return (
			<section>
				<Header name="Your Bots" description={description} />

				<div
					className={classNames('stories__list', {
						'stories__list--cards': true
					})}
				>
					<AddBot addBot={(name: string) => this.newBot(name)} isCard={true} autoFocus={true} />
					{myBots && myBots.map((bot, idx) => this.renderBot(bot, idx))}
				</div>
			</section>
		);
	}
}

const BotsQuery = gql`
	query BotsQuery {
		viewer {
			bots_created {
				emoji_id
				name
			}
		}
	}
`;

const NewBotMutation = gql`
	mutation createBot($name: String!) {
		createBot(name: $name) {
			emoji_id
			name
		}
	}
`;

const DeleteBotMutation = gql`
	mutation DeleteBot($emoji_id: String!) {
		deleteBot(emoji_id: $emoji_id) {
			name
		}
	}
`;

const wrapped = compose(
	graphql(BotsQuery, {
		name: 'botsQuery',
		options: {
			fetchPolicy: 'network-only'
		}
	}),
	graphql(NewBotMutation, {
		name: 'createBot' // name of the injected prop: this.props.feedQuery...
	}),
	graphql(DeleteBotMutation, {
		name: 'deleteBot'
	})
)(BotBuilderClass);

export default wrapped;
