import { connect } from 'react-redux'
import { bindActionCreators, Dispatch } from 'redux'

import { BDProductService, ProposalDataContext } from '@agiliza/api/domain'
import { StoreState } from '@agiliza/redux'
import * as entProposalDataContext from '@agiliza/redux/entities/proposalData/context'
import * as entProposalData from '@agiliza/redux/entities/proposalData/proposal'
import * as ucProposalData from '@agiliza/redux/useCases/proposalData/businessData'

export interface ConnectedProps {
  fetching: boolean
  productsServices: BDProductService[]
  getProductsServices: typeof ucProposalData.actions.getProductsServices
  addProductService: typeof ucProposalData.actions.addProductService
  updateProductService: typeof ucProposalData.actions.updateProductService
  context: ProposalDataContext
}

type StateProps = Pick<ConnectedProps, 'fetching' | 'context' | 'productsServices'>
type DispatchProps = Pick<ConnectedProps, 'getProductsServices' | 'addProductService' | 'updateProductService'>

const mapStateToProps = (state: StoreState): StateProps => ({
  fetching: ucProposalData.selectors.isFetching(state.useCases.proposalData.businessData),
  context: entProposalDataContext.selectors.getContext(state.entities.proposalData.context),
  productsServices: entProposalData.selectors.getProductsServices(state.entities.proposalData.proposal),
})

const mapDispatchToProps = (dispatch: Dispatch): DispatchProps =>
  bindActionCreators(
    {
      getProductsServices: ucProposalData.actions.getProductsServices,
      addProductService: ucProposalData.actions.addProductService,
      updateProductService: ucProposalData.actions.updateProductService,
    },
    dispatch
  )

export const connected = connect(mapStateToProps, mapDispatchToProps)
