import React from 'react';
import { connect } from 'react-redux';
import States from './States';
import { addState, deleteState, sortState, copyState } from 'models/panel';
import { updateScreen } from 'models/screens';

function StatesContainer({ panelId, current, states, screensById, addState, deleteState, updateScreen, sortState, copyState }) {
  const mappedStates = states
    .map((d) => {
      const screen = screensById[d];

      if (screen) {
        return {
          id: d,
          name: screen.name
        };
      } else {
        return null;
      }
    })
    .filter((d) => d);

  const handleSort = ({ oldIndex, newIndex }) => {
    sortState({
      id: panelId,
      oldIndex,
      newIndex
    });
  };

  return (
    <States
      current={current}
      states={mappedStates}
      onAdd={addState}
      onSort={handleSort}
      onNameUpdate={updateScreen}
      panelId={panelId}
      onDelete={deleteState}
      copyState={copyState}
    />
  );
}

const mapStateToProps = ({ createApp, panelsById, screensById, user }) => {
  const { id: screenId } = createApp;
  const screen = screensById[screenId];
  const states = (panelsById[screen.panelId] || { states: [] }).states;

  return {
    panelId: screen.panelId,
    screensById,
    states,
    current: screenId
  };
};

const mapDispatchToProps = {
  addState,
  updateScreen,
  deleteState,
  sortState,
  copyState
};

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