import * as React from 'react';

import { ChatEvent } from 'mweb/chat/events/baseChatEvent';
import Spinner from 'mweb/common/components/spinner';
import ChatPane from 'mweb/chat/components/chatPane';
import { SwitchToDesktop } from 'mweb/common/components/switchToDesktop';
import { DiscoverMore } from 'mweb/common/components/discoverMore';
import { withLatencyTracker } from 'mweb/common/latency/withLatencyTracker';
import {
  withCustomLatency,
  CustomLatencyProps,
} from 'mweb/common/latency/withCustomLatency';

export interface ChannelViewerBottomPaneProps extends CustomLatencyProps {
  showChat: boolean | undefined;
  isChatReady: boolean;
  game: string | undefined;
  switchToDesktop: React.EventHandler<React.MouseEvent<HTMLAnchorElement>>;
  chatMessages: ReadonlyArray<ChatEvent>;
}

export class ChannelViewerBottomPaneBase extends React.Component<
  ChannelViewerBottomPaneProps
> {
  static displayName: string = 'ChannelViewerBottomPane';
  hasReportedChatConnected: boolean = false;

  isInteractive(): boolean {
    return this.props.showChat === false || this.props.isChatReady;
  }

  componentDidMount(): void {
    this.checkForChatReporting();
  }

  componentDidUpdate(): void {
    this.checkForChatReporting();
  }

  checkForChatReporting(): void {
    if (
      !this.hasReportedChatConnected &&
      this.props.showChat &&
      this.props.isChatReady
    ) {
      this.props.reportLatencyEvent('chatConnected')();
      this.hasReportedChatConnected = true;
    }
  }

  render(): JSX.Element {
    if (this.props.showChat === false) {
      return (
        <div>
          <DiscoverMore game={this.props.game} />
          <SwitchToDesktop switchToDesktop={this.props.switchToDesktop} />
        </div>
      );
    }
    if (this.props.showChat && this.props.isChatReady) {
      return <ChatPane chatMessages={this.props.chatMessages} />;
    }
    return (
      <Spinner
        name="rotating-plane"
        wrapperClassName="channel-viewer__bottom-pane-spinner"
      />
    );
  }
}

export const ChannelViewerBottomPane = withCustomLatency(
  withLatencyTracker(ChannelViewerBottomPaneBase),
);
