import { makeStyles } from '@material-ui/core'
import { useState,useEffect } from 'react';
import { useSelector,useDispatch } from 'react-redux';
import ToolBar from './ToolBar'
import EditList from './EditList'
import SubmitBtn from './SubmitBtn';
import { getState } from '../../../../redux/authorization/selector'
import { asyncCurrentUser } from '../../../../redux/authorization/operations';
import { updateCredentials,updateUserAvatar } from '../../../../api-data';

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

interface IEditBar {
  setSelectedIndex: React.Dispatch<React.SetStateAction<number | null>>
}

const EditBar= ({setSelectedIndex}:IEditBar) => {
  const classes = useStyles()
  const dispatch = useDispatch()
  const user = useSelector(getState)
  const [name, setName] = useState<string>('')
  const [lastName, setLastName] = useState<string>('')
  const [openBtn, setOpenBtn] = useState<boolean>(false)
  const [file,setFile] = useState<any>(null)
  const {name:Name,lastName:LastName} = user

  const handleSubmit = async () => {
    if (name !== Name || lastName !== LastName){
      await updateCredentials({ name, lastName, originalName: name, originalLastName: lastName })
    }
    if (file) {
      const formData: any = new FormData()
      formData.append("avatar", file);
      await updateUserAvatar(formData)
    }
    file && setFile(null)
    openBtn && setOpenBtn(false)
    dispatch(asyncCurrentUser())
  }
  
  useEffect(() => {
    Name&&setName(Name)
    LastName && setLastName(LastName)
  }, [Name, LastName])  

    return (
    <div>
      <ToolBar setSelectedIndex={setSelectedIndex}/>
      <div className={classes.containerAbsolute}>
          <EditList user={user} name={name} setName={setName}
            lastName={lastName} setLastName={setLastName} 
            openBtn={openBtn} setOpenBtn={setOpenBtn}
            file={file} setFile={setFile}/>
          {openBtn&&<SubmitBtn handleSubmit={handleSubmit}/>}
      </div>
   </div>
  )
}

export default EditBar