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 { TiktokInsight } 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 {
  makeInsightDataSelector,
  makeInsightVisibilitySelector,
} from '../selectors';
import { TRootTrackPlaylistsState, TState } from '../types';
import { TState as TTrackState } from '../../track/types';
import { makeRefreshSelector } from '../../tiktok/selectors';
import { TEntityVisibility } from '../../common/types';
import { composeContexts } from '../../common/utils/react-better-context';
import { ContextInsight } from '../contexts';

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

const mapStateToProps = createStructuredSelector<
  TRootTrackPlaylistsState,
  TStructured
>({
  entity: makeInsightDataSelector(),
  lastStreamDate: makeLastStreamDateSelector(),
  globalRefresh: makeRefreshSelector(),
  insightVisibility: makeInsightVisibilitySelector(),
  //†prop
});
const mapDispatchToProps = {
  getInsight: ACTION.getInsight,
  //†action
};

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

  if (insightVisibility.offline) return null;

  const { globalRefresh } = rest;

  return composeContexts(
    [
      [
        ContextInsight,
        {
          entity,
          visibility: insightVisibility,
          refresh: globalRefresh,
        },
      ],
    ],
    <TiktokInsight />
  );
};

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