import React, { useEffect } from 'react';
import { connect } from 'react-redux';
import { compose } from 'redux';
import { createStructuredSelector } from 'reselect';
import { Intro } from '../components/intro';
import { withErrorBoundary } from '../../common/hoc/with-error-boundary';
import {
  TRootWelcomeSurvey,
  TSaveUserResponse,
  TSetVariant,
  TState,
} from '../types';
import { withReducer } from '../../app/core/with-reducer';
import reducer, { ACTION } from '../reducer';
import { withEpics } from '../../app/core/with-epics';
import * as epics from '../epics';
import { makeShowIntroSelector, makeSurveySelector } from '../selectors';
import { useScreenOrientation } from '../../common/hooks/use-screen-orientation';
import { updateNpsIntroSurveyAnalytics } from '../services';

type TPropsExternal = {};
type TStructured = {
  showIntro: boolean;
  survey: TState['survey'];
};
type TConnected = TPropsExternal &
  TStructured & {
    // getSurvey: () => void;
    setStep: (step: number) => void;
    setVariant: TSetVariant;
    saveUserResponse: TSaveUserResponse;
  };

const mapStateToProps = createStructuredSelector<
  TRootWelcomeSurvey,
  TStructured
>({
  // prop1: makeSelector(),
  showIntro: makeShowIntroSelector(),
  survey: makeSurveySelector(),
  //†prop
});
const mapDispatchToProps = {
  // getSurvey: ACTION.getSurvey,
  setStep: ACTION.setStep,
  setVariant: ACTION.setVariant,
  saveUserResponse: ACTION.saveUserResponse,
  //†action
};

const Connected: React.FC<TConnected> = ({ showIntro, survey, ...props }) => {
  const { isLandscape } = useScreenOrientation();

  useEffect(() => {
    if (showIntro && !isLandscape) {
      updateNpsIntroSurveyAnalytics(survey);
    }
  }, [showIntro, isLandscape]);

  if (!showIntro || isLandscape) {
    return null;
  }

  return <Intro survey={survey} {...props} />;
};

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