import React, { useEffect } from 'react'

import { ProposalDataContext, Reference } from '@agiliza/api/domain'
import ButtonWithProgress from '@agiliza/components/atoms/ButtonWithProgress'
import { ActionType } from '@agiliza/utils/hooks/state'
import {
  Button,
  Dialog as MUIDialog,
  DialogActions,
  DialogContent,
  DialogProps,
  DialogTitle
} from '@material-ui/core'
import { withStyles, WithStyles } from '@material-ui/core/styles'

import Form from '../Form'
import { CDReferenceState, initialState } from '../state'
import styles from './styles'

type ExtendedProps = Pick<DialogProps, 'open'> & WithStyles<typeof styles>

interface Props extends ExtendedProps {
  state: CDReferenceState
  actions: ActionType<CDReferenceState>
  onClose: () => void
  reference?: Reference
  onSave(rfc: Reference, add: boolean): () => void
  context: ProposalDataContext
  fetching: boolean
}

const Dialog = (props: Props) => {
  const { classes, fetching, open, onClose, onSave, reference, context, state, actions } = props

  useEffect(() => {
    if (reference) actions.update(reference)
    else actions.update(initialState)
  }, [reference])

  const mapStateToReference = (): Reference => {
    return state
  }

  return (
    <MUIDialog onClose={onClose} aria-labelledby="simple-dialog-title" open={open} PaperProps={{ className: classes.dialog }}>
      <DialogTitle>{reference ? 'Editar' : 'Adicionar'} pessoa envolvida</DialogTitle>
      <DialogContent>
        <Form state={state} actions={actions} context={context} />
      </DialogContent>
      <DialogActions>
        <Button onClick={onClose}>Cancelar</Button>
        <ButtonWithProgress variant="text" fetching={fetching} onClick={onSave(mapStateToReference(), !reference)}>
          Salvar
        </ButtonWithProgress>
      </DialogActions>
    </MUIDialog>
  )
}

export default withStyles(styles)(Dialog)
