import { connect } from 'react-redux'

import { SimulationCategory } from '@agiliza/api/domain'
import { StoreState } from '@agiliza/redux'
import * as entSimulationContext from '@agiliza/redux/entities/simulation/context'
import { actions as errorActions } from '@agiliza/redux/ui/error'
import * as uiSimulation from '@agiliza/redux/ui/simulation'
import * as ucSimulation from '@agiliza/redux/useCases/simulation'
import { bindActionCreators, Dispatch } from '@reduxjs/toolkit'

export interface ConnectedProps {
  fetching: boolean
  simulationCategories: SimulationCategory[]
  fetchSimulationCategories: typeof ucSimulation.actions.fetchSimulationCategories
  getSubproducts: typeof ucSimulation.actions.getSubproducts
  setErrorMessage: typeof errorActions.setErrorMessage
  setData: typeof uiSimulation.actions.setData
}

type StateProps = Pick<ConnectedProps, 'fetching' | 'simulationCategories'>
type DispatchProps = Pick<ConnectedProps, 'fetchSimulationCategories' | 'getSubproducts' | 'setErrorMessage' | 'setData'>

const mapStateToProps = (state: StoreState): StateProps => ({
  fetching: ucSimulation.selectors.isFetching(state.useCases.simulation),
  simulationCategories: entSimulationContext.selectors.getSimulationCategories(state.entities.simulation.context),
})

const mapDispatchToProps = (dispatch: Dispatch): DispatchProps =>
  bindActionCreators(
    {
      fetchSimulationCategories: ucSimulation.actions.fetchSimulationCategories,
      getSubproducts: ucSimulation.actions.getSubproducts,
      setErrorMessage: errorActions.setErrorMessage,
      setData: uiSimulation.actions.setData,
    },
    dispatch
  )

export const connected = connect(mapStateToProps, mapDispatchToProps)
