import React, { useEffect } from 'react'

import { BDProductService } 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
  productService?: BDProductService
  onSave(rfc: BDProductService, add: boolean): () => void
  fetching: boolean
}

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

  const formState = useFormState('VehicleForm', initialState)

  const { actions } = formState

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

  const mapStateToProductService = (): BDProductService => {
    return formState.state
  }

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

export default withStyles(styles)(Dialog)
