import React 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 { YoutubeDemographics } from '../components';
import reducer, { ACTION } from '../reducer';
import * as epics from '../epics';
import { makeLastStreamDateSelector } from '../../common/selectors/stream-latest-date/stream-latest-date-selectors';
import { withErrorBoundary } from '../../common/hoc/with-error-boundary';
import {
  makeDemographicsDataSelector,
  makeDemographicsVisibilitySelector,
} from '../selectors';
import { TRootTrackPlaylistsState, TState } from '../types';
import { TState as TTrackState } from '../../track/types';
import { makeRefreshSelector } from '../../youtube/selectors';
import { TEntityVisibility } from '../../common/types';
import { composeContexts } from '../../common/utils/react-better-context';
import { ContextDemographics } from '../contexts';

type TStructured = {
  entity: TState['demographics'];
  lastStreamDate: string | undefined;
  globalRefresh: TTrackState['refresh'];
  demographicsVisibility: TEntityVisibility;
};
type TConnected = TStructured & {
  getDemographics: () => void;
};
type TPropsExternal = {};

const mapStateToProps = createStructuredSelector<
  TRootTrackPlaylistsState,
  TStructured
>({
  entity: makeDemographicsDataSelector(),
  lastStreamDate: makeLastStreamDateSelector(),
  globalRefresh: makeRefreshSelector(),
  demographicsVisibility: makeDemographicsVisibilitySelector(),
  //†prop
});
const mapDispatchToProps = {
  getDemographics: ACTION.getDemographics,
  //†action
};

const Connected: React.FC<TConnected> = ({ ...rest }) => {
  const { entity, demographicsVisibility } = rest;

  if (demographicsVisibility.offline) return null;

  const { globalRefresh } = rest;

  return composeContexts(
    [
      [
        ContextDemographics,
        {
          entity,
          visibility: demographicsVisibility,
          refresh: globalRefresh,
        },
      ],
    ],
    <YoutubeDemographics />
  );
};

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