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

import { ProposalDataContext, Vehicle } 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
  vehicles: Vehicle[]
  getVehicles: typeof ucProposalData.actions.getVehicles
  addVehicle: typeof ucProposalData.actions.addVehicle
  updateVehicle: typeof ucProposalData.actions.updateVehicle
  context: ProposalDataContext
}

type StateProps = Pick<ConnectedProps, 'fetching' | 'context' | 'vehicles'>
type DispatchProps = Pick<ConnectedProps, 'getVehicles' | 'addVehicle' | 'updateVehicle'>

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

const mapDispatchToProps = (dispatch: Dispatch): DispatchProps =>
  bindActionCreators(
    {
      getVehicles: ucProposalData.actions.getVehicles,
      addVehicle: ucProposalData.actions.addVehicle,
      updateVehicle: ucProposalData.actions.updateVehicle,
    },
    dispatch
  )

export const connected = connect(mapStateToProps, mapDispatchToProps)
