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 { MarketKpi, TProps as TMarketKpiProps } from '../components/market-kpi';
import reducer, { ACTION } from '../reducer';
import * as epics from '../epics';
import { withErrorBoundary } from '../../common/hoc/with-error-boundary';
import {
  makeVisibilityConfigSelector,
  makeMarketKpiDataSelector,
} from '../selectors';
import { makeOfflineSelector } from '../../market/selectors';
import { TKpiDatas, TRootMarketKpi, TVisibility } from '../types';

const mapStateToProps = createStructuredSelector<
  TRootMarketKpi,
  {
    visibility: TVisibility;
    data: TKpiDatas;
    offline: boolean;
  }
>({
  visibility: makeVisibilityConfigSelector(),
  data: makeMarketKpiDataSelector(),
  offline: makeOfflineSelector(),
  //†prop
});
const mapDispatchToProps = {
  // getData: ACTION.getData,
  flush: ACTION.flush,
  refresh: ACTION.refresh,
  //†action
};

type TComposeConnection = {
  getData: () => void;
  flush: () => void;
  offline: boolean;
};

// Uncomment to write componentDidMount hook
const Connected = ({
  flush,
  offline,
  ...rest
}: TComposeConnection & TMarketKpiProps) => {
  useEffect(() => {
    return () => flush();
  }, []);

  if (offline) {
    return null;
  }

  return <MarketKpi {...rest} />;
};

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