import React, { useCallback, useEffect } from 'react'

import { InvolvedPerson, InvolvedPersonType } from '@agiliza/api/domain'
import { useFormState } from '@agiliza/utils/hooks/state'
import {
  Button,
  Dialog,
  DialogActions,
  DialogContent,
  DialogProps,
  DialogTitle
} from '@material-ui/core'
import { withStyles, WithStyles } from '@material-ui/core/styles'

import Customer from '../Customer'
import { initialState } from './state'
import styles from './styles'

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

interface Props extends ExtendedProps {
  person?: InvolvedPerson
  type?: InvolvedPersonType
  onSave(person?: InvolvedPerson): () => void
  onClose: () => void
}

const AddUpdateDialog = (props: Props) => {
  const { classes, open, onClose, type, person, onSave } = props

  const { actions, state } = useFormState('involvedPersonForm', initialState)

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

  const renderForm = useCallback(
    (type: InvolvedPersonType) => {
      switch (type) {
        case 'CUSTOMER':
          return <Customer state={state} actions={actions} />
      }
    },
    [type, state]
  )

  const mapStateToPerson = (): InvolvedPerson | undefined => {
    const { hasAccount, ...identification } = state
    return type && { id: person?.id || '', identification: { ...identification, type } }
  }

  return (
    <Dialog onClose={onClose} aria-labelledby="simple-dialog-title" open={open} PaperProps={{ className: classes.dialog }}>
      <DialogTitle>{person ? 'Editar' : 'Adicionar'} pessoa envolvida</DialogTitle>
      <DialogContent>{type && renderForm(type)}</DialogContent>
      <DialogActions>
        <Button onClick={onClose}>Cancelar</Button>
        <Button onClick={onSave(mapStateToPerson())}>Salvar</Button>
      </DialogActions>
    </Dialog>
  )
}

export default withStyles(styles)(AddUpdateDialog)
