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 SubmitBtn from './SubmitBtn';
import { getState } from '../../../../redux/authorization/selector'
import { updateCredentials,updateUserAvatar } from '../../../../api-data';

const useStyles = makeStyles({
  container: {
    width: '100%',
    height: '100%',
    backgroundColor: '#f3f2f2',
    position:'relative'
  }
})

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

const EditBar= ({setSelectedIndex}:IEditBar) => {
  const classes = useStyles()
  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)
  }
  
  useEffect(() => {
    Name&&setName(Name)
    LastName && setLastName(LastName)
  }, [Name, LastName])  

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

export default EditBar