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

import { ProposalDataContext, Reference } 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/customerData'

export interface ConnectedProps {
  fetching: boolean
  references: Reference[]
  getReferences: typeof ucProposalData.actions.getReferences
  addReference: typeof ucProposalData.actions.addReference
  updateReference: typeof ucProposalData.actions.updateReference
  context: ProposalDataContext
}

type StateProps = Pick<ConnectedProps, 'fetching' | 'context' | 'references'>
type DispatchProps = Pick<ConnectedProps, 'getReferences' | 'addReference' | 'updateReference'>

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

const mapDispatchToProps = (dispatch: Dispatch): DispatchProps =>
  bindActionCreators(
    {
      getReferences: ucProposalData.actions.getReferences,
      addReference: ucProposalData.actions.addReference,
      updateReference: ucProposalData.actions.updateReference,
    },
    dispatch
  )

export const connected = connect(mapStateToProps, mapDispatchToProps)
