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 { TrackChartsScreen } from '../components/track-charts-screen';
import reducer, { ACTION } from '../reducer';
import * as epics from '../epics';
import { withErrorBoundary } from '../../common/hoc/with-error-boundary';
import { makeVisibilityConfigSelector, makeChartsSelector } from '../selectors';
import { updatePageMeta, PAGES } from '../../analytics';
import { withNavigationSync } from '../../common/hoc/with-navigation-sync';
import { useNavKeyMap } from '../../common/hooks/use-nav-key-map';
import { ROUTES } from '../../app/constants';
import {
  TRootTrackChartsScreenState,
  TRoute,
  TState,
  TVisibility,
} from '../types';
import { NEntityInfinite } from '../../common/types';
import { FETCH_TYPE } from '../../common/constants';
import { SORT_BY } from '../constants';

type TStructured = {
  charts: TState['charts'];
  visibility: TVisibility;
};

type TConnected = TStructured &
  TPropsExternal & {
    getData: NEntityInfinite.TEntityInfiniteGet;
    flush: () => void;
    route: TRoute;
    setConfig: (config: { sortBy?: SORT_BY }) => void;
  };

type TPropsExternal = {};

const mapStateToProps = createStructuredSelector<
  TRootTrackChartsScreenState,
  TStructured
>({
  charts: makeChartsSelector(),
  visibility: makeVisibilityConfigSelector(),
  //†prop
});
const mapDispatchToProps = {
  getData: ACTION.getCharts,
  setConfig: ACTION.setConfig,
  flush: ACTION.flush,
  //†action
};

// Uncomment to write componentDidMount hook
const Connected: React.FC<TConnected> = ({ getData, flush, ...rest }) => {
  const { route } = rest;

  const source = _.path('params.provider')(route);

  useNavKeyMap({ page: ROUTES.chartlists, route });

  useEffect(() => {
    getData({ sortBy: SORT_BY.rank }, FETCH_TYPE.force);

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

  useEffect(() => {
    updatePageMeta({
      page: PAGES.Chartlists.page,
      dsp_type: _.capitalize(source),
    });
  });

  return <TrackChartsScreen {...rest} getData={getData} />;
};

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