import { makeStyles } from '@material-ui/core'
import { useState,useEffect } from 'react';
import { useSelector } from 'react-redux';
import ToolBar from './ToolBar'
import EditList from './EditList'
import Delete from './Delete'
import SubmitBtn from './SubmitBtn';
import { getContactsMemo } from '../../../../../../redux/contacts/selector'
import { getChat } from '../../../../../../redux/chat/selector'
import { muteChat,updateContact } from '../../../../../../api-data';

const useStyles = makeStyles({
    containerAbsolute: {
        position: 'absolute',
        top: 58,
        width: 506,
        maxHeight: '905px',
        minHeight: '905px',
        overflow: 'hidden',
        backgroundColor: '#f3f2f2',
    }
})

const EditBar= () => {
  const classes = useStyles()
  const contactsMemo = useSelector(getContactsMemo)
  const chat = useSelector(getChat)
  const [isContact, setIsContact] = useState<any>(false)
  const [name, setName] = useState<string>('')
  const [lastName, setLastName] = useState<string>('')
  const [mute, setMute] = useState<boolean>(true)
  const [openBtn, setOpenBtn] = useState<boolean>(false)
  const {name:Name,lastName:LastName,mute:Mute,companionId,_id} = chat

  const handleSubmit = () => {
    if (mute !== !Mute) {
      muteChat(companionId)
    }
    if (name !== Name || lastName !== LastName) {
      updateContact(isContact._id,_id,name,lastName)
    }    
    openBtn&&setOpenBtn(false)
  }

  useEffect(() => {
    const contact = contactsMemo.find((el) => el.number === chat.number)
    contact && setIsContact(contact)    
  }, [contactsMemo, chat.number])
  
  useEffect(() => {
    Name&&setName(Name)
    LastName && setLastName(LastName)
    setMute(!Mute)
  }, [Name, LastName, Mute])  

    return (
    <div>
      <ToolBar />
      <div className={classes.containerAbsolute}>
          <EditList chat={chat} name={name} setName={setName} lastName={lastName}
            setLastName={setLastName} mute={mute} setMute={setMute}
            openBtn={openBtn} setOpenBtn={setOpenBtn} />
          <Delete _id={isContact._id} />
          {openBtn&&<SubmitBtn handleSubmit={handleSubmit}/>}
      </div>
   </div>
  )
}

export default EditBar