import React, { useState } from 'react'

import { BDProductService } from '@agiliza/api/domain'
import { ActionType } from '@agiliza/utils/hooks/state'
import { Avatar, List, ListItem, ListItemAvatar, ListItemText } from '@material-ui/core'
import { withStyles, WithStyles } from '@material-ui/core/styles'
import { Add as AddIcon, Apps as AppsIcon } from '@material-ui/icons'

import { connected, ConnectedProps } from './connect'
import Dialog from './Dialog'
import { BDProductServiceState } from './state'
import styles from './styles'

type ExtendedProps = WithStyles<typeof styles> & ConnectedProps

interface Props extends ExtendedProps {
  projectId: string
  state: BDProductServiceState
  actions: ActionType<BDProductServiceState>
}

const ProductsServices = (props: Props) => {
  const { classes, fetching, projectId, productsServices } = props

  const [selectedProductService, setSelectedProductService] = useState<BDProductService | undefined>()

  const [open, setOpen] = useState(false)

  const handleClickListItem = (productService: BDProductService) => () => {
    setOpen(true)
    setSelectedProductService(productService)
  }

  const handleClickAdd = () => {
    setOpen(true)
    setSelectedProductService(undefined)
  }
  const handleClickClose = () => {
    setOpen(false)
    setSelectedProductService(undefined)
  }

  const handleSave = (productService: BDProductService, add: boolean) => () => {
    const onSuccess = () => {
      setOpen(false)
      setSelectedProductService(productService)
    }
    if (add) props.addProductService({ projectId, productService, onSuccess })
    else props.updateProductService({ projectId, productServiceId: productService.id, productService, onSuccess })
  }

  return (
    <>
      <div className={classes.contentContainer}>
        <div className={classes.content}>
          <List className={classes.list}>
            {productsServices.map((vehicle, i) => (
              <ListItem key={i} button onClick={handleClickListItem(vehicle)}>
                <ListItemAvatar>
                  <Avatar>
                    <AppsIcon />
                  </Avatar>
                </ListItemAvatar>
                <ListItemText primary={vehicle.description} />
              </ListItem>
            ))}
          </List>
        </div>
      </div>
      <Avatar className={classes.avatarBtnContainer} onClick={handleClickAdd}>
        <AddIcon />
      </Avatar>
      <Dialog fetching={fetching} open={open} onClose={handleClickClose} productService={selectedProductService} onSave={handleSave} />
    </>
  )
}

export default connected(withStyles(styles)(ProductsServices))
