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

import { Reference } from '@agiliza/api/domain/proposalData/involvedPeople/reference'
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, EmojiEmotions as EmojiEmotionsIcon } from '@material-ui/icons'

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

type ExtendedProps = WithStyles<typeof styles> & ConnectedProps

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

const References = (props: Props) => {
  const { classes, fetching, context, state, actions, references, projectId, personId } = props

  console.log(personId)

  const [selectedReference, setSelectedReference] = useState<Reference | undefined>()

  const [open, setOpen] = useState(false)

  useEffect(() => {
    props.getReferences({ personId, projectId })
  }, [])

  const handleClickListItem = (reference: Reference) => () => {
    setOpen(true)
    setSelectedReference(reference)
  }

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

  const handleSave = (reference: Reference, add: boolean) => () => {
    const onSuccess = () => {
      setOpen(false)
      setSelectedReference(reference)
    }
    if (add)
      props.addReference({
        projectId,
        personId,
        reference,
        onSuccess,
      })
    else
      props.updateReference({
        projectId,
        personId,
        referenceId: reference.id,
        reference,
        onSuccess,
      })
  }

  return (
    <>
      <div className={classes.contentContainer}>
        <div className={classes.content}>
          <List className={classes.list}>
            {references.map((reference, i) => (
              <ListItem key={i} button onClick={handleClickListItem(reference)}>
                <ListItemAvatar>
                  <Avatar>
                    <EmojiEmotionsIcon />
                  </Avatar>
                </ListItemAvatar>
                <ListItemText primary={reference.name} secondary={reference.extraInfo} />
              </ListItem>
            ))}
          </List>
        </div>
      </div>
      <Avatar className={classes.avatarBtnContainer} onClick={handleClickAdd}>
        <AddIcon />
      </Avatar>
      <Dialog
        fetching={fetching}
        open={open}
        onClose={handleClickClose}
        reference={selectedReference}
        onSave={handleSave}
        context={context}
        state={state}
        actions={actions}
      />
    </>
  )
}

export default connected(withStyles(styles)(References))
