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 { getAuthorizationState } from '../../../../redux/authorization/selector'
import { asyncCurrentUser } from '../../../../redux/authorization/operations';
import { updateCredentials, updateUserAvatar } from '../../../../api-data';
import { refreshAppTime } from '../../../../helpers';

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



const EditBar= () => {
  const classes = useStyles()
  const dispatch = useDispatch()
  const user = useSelector(getAuthorizationState)
  const [name, setName] = useState<string>('')
  const [lastName, setLastName] = useState<string>('')
  const [openBtn, setOpenBtn] = useState<boolean>(false)
  const [camera, setCamera] = useState<boolean>(false)
  const [selfie, setSelfie] = useState<any>(null)
  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 (selfie) {
      fetch(selfie)
       .then(res => res.blob())
        .then(blob => {
          const imgFile = new File([blob], "selfie", { type: "image/jpeg" })
          const formData: any = new FormData()
          formData.append("avatar", imgFile);
          updateUserAvatar(formData)
      })
    }
    if (file) {
      const formData: any = new FormData()
      formData.append("avatar", file);
      await updateUserAvatar(formData)
    }
    file && setFile(null)
    selfie && setSelfie(null)
    openBtn && setOpenBtn(false)
  }

  useEffect(() => {
    const handleReset = () => !openBtn && dispatch(asyncCurrentUser())
    handleReset()
    const idInterval = setInterval(handleReset, refreshAppTime);
    return () => clearInterval(idInterval);
  }, [openBtn,dispatch]);  
  
  useEffect(() => {
    Name&&setName(Name)
    LastName && setLastName(LastName)
  }, [Name, LastName])

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

export default EditBar