import * as React from 'react';
import { connect } from 'react-redux';
import { bindActionCreators, Dispatch } from 'redux';
import Helmet from 'react-helmet';

import { isChatReady, RootState, isOnClient } from 'mweb/common/reducers/root';
import { getChannelDetails } from 'mweb/common/selectors/data/channels';
import HeadContainer from 'mweb/common/containers/head';
import Spinner from 'mweb/common/components/spinner';
import ChatPane from 'mweb/chat/components/chatPane';
import { ChatEmbedOptions } from 'mweb/chat/chatReducer';
import { ChatEvent } from 'mweb/chat/events/baseChatEvent';
import { buildChannelPath } from 'mweb/common/utils/pathBuilders';
import { chatEmbedPageTransitionClient } from 'mweb/common/actions/pages/chatEmbed';

if (process.env.BROWSER) {
  require('./chatEmbed.sass');
}

export interface ChatEmbedStateProps {
  isChatReady: boolean;
  chatMessages: ReadonlyArray<ChatEvent>;
  chatEmbedOptions: ChatEmbedOptions | undefined;
  channelName: string;
  channelDisplayName: string;
  isOnClient: boolean;
}

export interface ChatEmbedDispatchProps {
  transition: () => void;
}

export interface ChatEmbedProps
  extends ChatEmbedStateProps,
    ChatEmbedDispatchProps {}

class ChatEmbedBase extends React.Component<Readonly<ChatEmbedProps>, {}> {
  componentDidMount(): void {
    this.props.transition();
  }

  content(): JSX.Element | undefined {
    if (!this.props.isOnClient) {
      return undefined;
    }

    if (!this.props.isChatReady) {
      return (
        <Spinner name="rotating-plane" wrapperClassName="chat-embed-spinner" />
      );
    }

    return (
      <ChatPane
        chatMessages={this.props.chatMessages}
        chatEmbedOptions={this.props.chatEmbedOptions}
      />
    );
  }

  render(): JSX.Element {
    return (
      <div className="chat-embed">
        <Helmet>
          <title>
            {`${this.props.channelDisplayName || ''} chat - Twitch`.trim()}
          </title>
        </Helmet>
        <HeadContainer path={buildChannelPath(this.props.channelName)} />
        {this.content()}
      </div>
    );
  }
}

function mapStateToProps(state: RootState): ChatEmbedStateProps {
  const channel = getChannelDetails(
    state,
    state.pages.chatEmbed.currentChannel,
  );
  return {
    isChatReady: isChatReady(state),
    chatMessages: state.chat.messages,
    chatEmbedOptions: state.chat.embedOptions,
    channelName: channel ? channel.name : state.pages.chatEmbed.currentChannel,
    channelDisplayName: channel
      ? channel.displayName
      : state.pages.chatEmbed.currentChannel,
    isOnClient: isOnClient(state),
  };
}

function mapDispatchToProps(
  dispatch: Dispatch<RootState>,
): ChatEmbedDispatchProps {
  return bindActionCreators(
    {
      transition: chatEmbedPageTransitionClient,
    },
    dispatch,
  );
}

export const ChatEmbed = connect(mapStateToProps, mapDispatchToProps)(
  ChatEmbedBase,
) as React.ComponentClass<{}>;
