import React, { useEffect, useState } from 'react';
import { Dimensions } from 'react-native';
import { connect } from 'react-redux';
import { compose } from 'redux';
import { createStructuredSelector } from 'reselect';
import { fromEventPattern } from 'rxjs';
import { withEpics } from '../../app/core/with-epics';
import { withReducer } from '../../app/core/with-reducer';
import { withErrorBoundary } from '../../common/hoc/with-error-boundary';
import * as epics from '../epics';
import reducer from '../reducer';
import { fp as _ } from '../../common/utils/fp';
import { makeIsOtaUpdateScreenShownSelector } from '../selectors';
import { ENV } from '../../../env';
import { TRootUpdaterState, TState, TToggleOtaUpdateScreen } from '../types';
import { OtaUpdateScreen } from '../components/ota-update-screen';

type TPropsExternal = {};
type TStructured = {
  isOtaUpdateScreenShown: TState['isOtaUpdateScreenShown'];
};
type TConnected = TPropsExternal &
  TStructured & {
    toggleOtaUpdateScreen: TToggleOtaUpdateScreen;
  };

const mapStateToProps = createStructuredSelector<
  TRootUpdaterState,
  TStructured
>({
  isOtaUpdateScreenShown: makeIsOtaUpdateScreenShownSelector(),
  // changelog: makeChangelogSelector(),
  //†prop
});
const mapDispatchToProps = {
  //†action
};

const Connected: React.FC<TConnected> = ({
  isOtaUpdateScreenShown,
  ...rest
}) => {
  const [isLandscape, setIsLandscape] = useState<boolean | null>(null);
  const setLandscape = () => {
    const { width, height } = Dimensions.get('window');
    setIsLandscape(width > height);
  };

  useEffect(() => {
    setLandscape();
  }, [isOtaUpdateScreenShown]);

  useEffect(() => {
    const sub = fromEventPattern(
      handler => Dimensions.addEventListener('change', handler),
      (handler, subscription) => subscription.remove()
    ).subscribe(setLandscape);
    return () => sub.unsubscribe();
  }, []);

  if (!isOtaUpdateScreenShown) {
    return null;
  }

  return <OtaUpdateScreen {...rest} isLandscape={isLandscape} />;
};

export default compose(
  withReducer('updater', reducer),
  ENV!.features.devDisableSplash ? _.identity : withEpics('updater', epics),
  withErrorBoundary('updater:otaUpdateScreen'),
  connect(
    mapStateToProps,
    mapDispatchToProps
  )
)(Connected) as React.FC<TPropsExternal>;
