import React, { useEffect } from 'react'

import { Vehicle } from '@agiliza/api/domain'
import ButtonWithProgress from '@agiliza/components/atoms/ButtonWithProgress'
import { useFormState } 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 { initialState } from '../state'
import styles from './styles'

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

interface Props extends ExtendedProps {
  onClose: () => void
  vehicle?: Vehicle
  onSave(rfc: Vehicle, add: boolean): () => void
  fetching: boolean
}

const Dialog = (props: Props) => {
  const { classes, fetching, open, onClose, onSave, vehicle } = props

  const formState = useFormState('VehicleForm', initialState)

  const { actions } = formState

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

  const mapStateToVehicle = (): Vehicle => {
    return formState.state
  }

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

export default withStyles(styles)(Dialog)
