import React from 'react';
import { connect } from 'react-redux';
import { compose } from 'redux';
import { createStructuredSelector } from 'reselect';
import { Nullable } from 'tsdef';
import { withReducer } from '../../app/core/with-reducer';
import { withEpics } from '../../app/core/with-epics';
import { fp as _ } from '../../common/utils/fp';
import { TrackCharts } from '../components/track-charts';
import reducer from '../reducer';
import * as epics from '../epics';
import { withErrorBoundary } from '../../common/hoc/with-error-boundary';
import {
  makeVisibilityConfigSelector,
  makeAppleTotalSelector,
  makeAppleTopMarketSelector,
  makeSpotifyTotalSelector,
  makeSpotifyTopMarketSelector,
} from '../selectors';
import { makeErrorGlobalSelector } from '../../track/selectors';
import { TRootTrackChartsState, TVisibility } from '../types';

type TStructured = {
  visibility: TVisibility;
  spotifyTotal: number;
  spotifyTopMarket: Nullable<string>;
  appleTotal: number;
  appleTopMarket: Nullable<string>;
  globalError: boolean;
};

type TConnected = TStructured & TPropsExternal & {};

type TPropsExternal = {};

const mapStateToProps = createStructuredSelector<
  TRootTrackChartsState,
  TStructured
>({
  visibility: makeVisibilityConfigSelector(),
  spotifyTotal: makeSpotifyTotalSelector(),
  spotifyTopMarket: makeSpotifyTopMarketSelector(),
  appleTotal: makeAppleTotalSelector(),
  appleTopMarket: makeAppleTopMarketSelector(),
  globalError: makeErrorGlobalSelector(),
  //†prop
});

const mapDispatchToProps = {
  //†action
};

// Uncomment to write componentDidMount hook
const Connected: React.FC<TConnected> = ({ globalError, ...rest }) => {
  if (globalError) return null;
  return <TrackCharts {...rest} />;
};

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