import React, { useState } from 'react'

import { Vehicle } 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, DriveEta as DriveEtaIcon } from '@material-ui/icons'

import { connected, ConnectedProps } from './conect'
import Dialog from './Dialog'
import { CDVehicleState } from './state'
import styles from './styles'

type ExtendedProps = WithStyles<typeof styles> & ConnectedProps

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

const Vehicles = (props: Props) => {
  const { classes, fetching, projectId, personId, vehicles } = props

  const [selectedVehicle, setSelectedVehicle] = useState<Vehicle | undefined>()

  const [open, setOpen] = useState(false)

  const handleClickListItem = (vehicle: Vehicle) => () => {
    setOpen(true)
    setSelectedVehicle(vehicle)
  }

  const handleClickAdd = () => {
    setOpen(true)
    setSelectedVehicle(undefined)
  }

  const handleClickClose = () => {
    setOpen(false)
    setSelectedVehicle(undefined)
  }

  const handleSave = (vehicle: Vehicle, add: boolean) => () => {
    const onSuccess = () => {
      setOpen(false)
      setSelectedVehicle(vehicle)
    }
    if (add)
      props.addVehicle({
        projectId,
        personId,
        vehicle,
        onSuccess,
      })
    else
      props.updateVehicle({
        projectId,
        personId,
        vehicleId: vehicle.id,
        vehicle,
        onSuccess,
      })
  }

  return (
    <>
      <div className={classes.contentContainer}>
        <div className={classes.content}>
          <List className={classes.list}>
            {vehicles.map((vehicle, i) => (
              <ListItem key={i} button onClick={handleClickListItem(vehicle)}>
                <ListItemAvatar>
                  <Avatar>
                    <DriveEtaIcon />
                  </Avatar>
                </ListItemAvatar>
                <ListItemText primary={vehicle.brand} secondary={vehicle.licensePlate} />
              </ListItem>
            ))}
          </List>
        </div>
      </div>
      <Avatar className={classes.avatarBtnContainer} onClick={handleClickAdd}>
        <AddIcon />
      </Avatar>
      <Dialog fetching={fetching} open={open} onClose={handleClickClose} vehicle={selectedVehicle} onSave={handleSave} />
    </>
  )
}

export default connected(withStyles(styles)(Vehicles))
