import React, { Suspense } from 'react';
import { connect } from 'react-redux';
import Screen from 'components/ScreenPreview';
import {
  ScreenProvider,
  ScreenDataProvider,
  PanelDataProvider,
  ComponentDataProvider,
  FilterDataProvider,
  CallbackProvider,
  InteractionProvider
} from 'components/ScreenPreview/Context';
import { getComponentData } from 'models/component';
import { emitCallback } from 'models/callback';
import { emitEvent, switchPanelState } from 'models/interaction';

function ScreenContainer({
  id,
  width,
  height,
  tenantId,
  screensById,
  componentsById,
  panelsById,
  filters,
  callbackKeys,
  callbackValues,
  interactions,
  getComponentData,
  emitEvent,
  emitCallback,
  switchPanelState
}) {
  return (
    <ScreenProvider
      getComponentData={getComponentData}
      emitEvent={emitEvent}
      emitCallback={emitCallback}
      tenantId={tenantId}
      switchPanelState={switchPanelState}
    >
      <ScreenDataProvider screensById={screensById}>
        <PanelDataProvider panelsById={panelsById}>
          <ComponentDataProvider componentsById={componentsById}>
            <CallbackProvider callbackKeys={callbackKeys} callbackValues={callbackValues}>
              <FilterDataProvider filters={filters}>
                <InteractionProvider interactions={interactions}>
                  <Suspense fallback="">
                    <Screen id={id} width={width} height={height} />
                  </Suspense>
                </InteractionProvider>
              </FilterDataProvider>
            </CallbackProvider>
          </ComponentDataProvider>
        </PanelDataProvider>
      </ScreenDataProvider>
    </ScreenProvider>
  );
}

const mapStateToProps = ({ user, panelDetail, componentsById, screensById, panelsById, filters, callback, interactions }) => {
  const { stateId, config } = panelDetail;
  const { callbackKeys, callbackValues } = callback;
  const { userInfo } = user;

  return {
    id: stateId,
    width: config.width,
    height: config.height,
    componentsById,
    tenantId: userInfo.tenantId,
    screensById,
    panelsById,
    filters: filters.list,
    callbackKeys,
    callbackValues,
    interactions
  };
};

const mapDispatchToProps = {
  getComponentData,
  emitCallback,
  emitEvent,
  switchPanelState
};

export default connect(mapStateToProps, mapDispatchToProps)(ScreenContainer);
