import * as React from 'react';
import { connect } from 'react-redux';

import { RootState, isOnClient } from 'mweb/common/reducers/root';
import { withLatencyTracker } from 'mweb/common/latency/withLatencyTracker';

interface ClientOnlyStateProps {
  isOnClient: boolean;
}

interface ClientOnlyOwnProps {
  hasLatencyTrackedChildren?: boolean;
  serverHeight?: string;
}

interface ClientOnlyProps extends ClientOnlyStateProps, ClientOnlyOwnProps {}

class ClientOnlyBase extends React.Component<ClientOnlyProps, {}> {
  static displayName: string = 'ClientOnly';

  latencyName: string | undefined;

  constructor(props: ClientOnlyProps) {
    super(props);
    this.latencyName = props.hasLatencyTrackedChildren
      ? 'CriticalClientOnly'
      : undefined;
  }

  isInteractive(): boolean {
    return !this.props.hasLatencyTrackedChildren || this.props.isOnClient;
  }

  render(): JSX.Element | null {
    if (!this.props.isOnClient) {
      if (this.props.serverHeight) {
        return <div style={{ height: this.props.serverHeight }} />;
      }

      return null;
    }
    return <div>{this.props.children}</div>;
  }
}

function mapStateToProps(state: RootState): ClientOnlyStateProps {
  return {
    isOnClient: isOnClient(state),
  };
}

export const ClientOnly = connect(mapStateToProps)(
  withLatencyTracker(ClientOnlyBase),
) as React.ComponentClass<ClientOnlyOwnProps>;
