import React, { useEffect } from 'react';
import { connect } from 'react-redux';
import { compose } from 'redux';
import { createStructuredSelector } from 'reselect';
import { withReducer } from '../../app/core/with-reducer';
import { withEpics } from '../../app/core/with-epics';
import { fp as _ } from '../../common/utils/fp';
import { MarketMonitoring } from '../components';
import reducer, { ACTION } from '../reducer';
import * as epics from '../epics';
import { withErrorBoundary } from '../../common/hoc/with-error-boundary';
import {
  makeActiveStreamTabSelector,
  makeEntitiesSelector,
  makeVisibilityConfigSelector,
} from '../selectors';
import {
  makeDateRangeSelector,
  makeOfflineSelector,
} from '../../market/selectors';
import {
  TEntities,
  TEntityId,
  TPropsExternal,
  TRootStateMarketMonitoring,
  TVisibility,
} from '../types';
import { TCustomRangeEntity } from '../../common/types';

type TProps = {
  visibility: TVisibility;
  range?: TCustomRangeEntity;
  activeTab: TEntityId;
  entities: TEntities;
  offline: boolean;
};

const mapStateToProps = createStructuredSelector<
  TRootStateMarketMonitoring,
  TProps
>({
  visibility: makeVisibilityConfigSelector(),
  range: makeDateRangeSelector(),
  activeTab: makeActiveStreamTabSelector(),
  entities: makeEntitiesSelector(),
  offline: makeOfflineSelector(),
  //†prop
});
const mapDispatchToProps = {
  flush: ACTION.flush,
  setActiveTab: ACTION.setActiveTab,
  //†action
};

type TPropsConnected = TProps & {
  flush: () => void;
  setActiveTab: (id: TEntityId) => void;
  scrollToBottom: (withoutAnimation?: boolean) => void;
};

// Uncomment to write componentDidMount hook
const Connected: React.FC<TPropsConnected> = ({
  flush,
  setActiveTab,
  activeTab,
  offline,
  ...rest
}) => {
  const { visibility } = rest;

  useEffect(() => {
    return () => flush();
  }, []);

  if (offline) {
    return null;
  }

  return (
    <MarketMonitoring
      {...rest}
      visibility={visibility}
      setActiveTab={setActiveTab}
      activeTab={activeTab}
    />
  );
};

export default compose(
  _.hoistStatics(MarketMonitoring),
  withReducer('marketMonitoring', reducer),
  withEpics('marketMonitoring', epics),
  withErrorBoundary('marketMonitoring'),
  connect(
    mapStateToProps,
    mapDispatchToProps
  )
)(Connected) as React.FC<TPropsExternal>;
