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

import { Project, ProjectContext } from '@agiliza/api/domain'
import { StoreState } from '@agiliza/redux'
import * as entProject from '@agiliza/redux/entities/project'
import * as ucProject from '@agiliza/redux/useCases/project'

export interface ConnectedProps {
  fetching: boolean
  searching: boolean
  submitting: boolean
  context: ProjectContext
  projects: Project[]
  getContext: typeof ucProject.actions.getContext
  getProjects: typeof ucProject.actions.getProjects
  submitProjects: typeof ucProject.actions.submitProjects
}

type StateProps = Pick<ConnectedProps, 'context' | 'projects' | 'fetching' | 'searching' | 'submitting'>
type DispatchProps = Pick<ConnectedProps, 'getContext' | 'getProjects' | 'submitProjects'>

const mapStateToProps = (state: StoreState): StateProps => ({
  fetching: ucProject.selectors.isFetching(state.useCases.project),
  searching: ucProject.selectors.isSearching(state.useCases.project),
  submitting: ucProject.selectors.isSubmitting(state.useCases.project),
  context: entProject.selectors.getContext(state.entities.project),
  projects: entProject.selectors.getProjects(state.entities.project),
})

const mapDispatchToProps = (dispatch: Dispatch): DispatchProps =>
  bindActionCreators(
    {
      getContext: ucProject.actions.getContext,
      getProjects: ucProject.actions.getProjects,
      submitProjects: ucProject.actions.submitProjects,
    },
    dispatch
  )

export const connected = connect(mapStateToProps, mapDispatchToProps)
