import '../stylesheets/bbb/botbuilder.scss';
import '../stylesheets/story-card.scss';

import classNames from 'classnames';
import * as React from 'react';
import { Link } from 'react-router-dom';

class BotCard extends React.Component {
	public props: {
		deleteBot(id: string): void;
		bot: any;
	};
	constructor(props, context) {
		super(props, context);

		this.onClick = this.onClick.bind(this);
	}

	makeBotUrl(bot) {
		const tld = process.env.APP_DOMAIN;
		// @ts-ignore
		const protocol = tld.includes('localhost') ? 'http' : 'https';
	}

	render() {
		const { bot } = this.props;

		return (
			<Link className="story-card story-card--card" to={`/bots/${bot.emoji_id}`}>
				<div className={classNames('story-card__inner')}>
					<div className="story-card__title">{bot.name}</div>
					<div className="story-card__image bot_id">{bot.emoji_id}</div>
					<div className="story-card__no-messages">...</div>
					<div className="story-card__tools">
						<span className="story-card__delete icon-trash" onClick={(e) => this.deleteBot(e, bot.emoji_id)} />
					</div>
				</div>
			</Link>
		);
	}

	deleteBot(e, emoji_id) {
		this.props.deleteBot(emoji_id);
		return e.stopPropagation();
	}

	onClick(e) {
		e.stopPropagation();
		console.log('CLICK');
	}
}

export interface AddBotProps {
	autoFocus: boolean;
	isCard: boolean;
	addBot: (e) => void;
}

export class AddBot extends React.Component {
	static defaultProps = {
		autoFocus: false,
		isCard: true,
		addBot: (e) => console.log('Should be adding bot', e)
	};
	props: AddBotProps;
	_input: any;
	public state = {
		botName: ''
	};
	constructor(props, context) {
		super(props, context);

		this.onClick = this.onClick.bind(this);
		this.setRef = this.setRef.bind(this);
		this.onKeyUp = this.onKeyUp.bind(this);
		this.onCreateBot = this.onCreateBot.bind(this);
	}

	render() {
		const { autoFocus, isCard } = this.props;
		return (
			<div
				className={classNames('story-card story-card--form', {
					'story-card--list-item': !isCard
				})}
				onClick={this.onClick}
			>
				<div className="story-card__form-inner">
					<label className="story-card__form-label">Bot name</label>
					<input
						placeholder="Ex. My First Bot"
						type="text"
						className="story-card__form-input"
						ref={this.setRef}
						autoFocus={autoFocus}
						onKeyUp={this.onKeyUp}
					/>
				</div>
				<div className="btn btn--small btn--primary" onClick={this.onCreateBot}>
					Create Bot
				</div>
			</div>
		);
	}

	onCreateBot(e) {
		this.props.addBot(this.state.botName);
	}

	onKeyUp(event) {
		if (event.which === 13) {
			if (event.target.value === '') return;
			event.target.blur();
			this.props.addBot(this.state.botName);
			return;
		}
		this.setState({ botName: event.target.value });
	}

	onClick() {
		if (!this._input) return;
		this._input.focus();
	}

	setRef(el) {
		this._input = el;
	}
}

export default BotCard;
