import {useSelector} from'react-redux'
import { useEffect, useRef, useState } from 'react'
import {getDownloadURL, getStorage, ref, uploadBytesResumable} from 'firebase/storage'
import { app } from '../firebase';

export const Profile = () => {
  const fileRef = useRef(null);
  const {currentUser} = useSelector((state) => state.user);
  const [file, setFile] = useState(undefined);
  const [filePercentage, setFilePercentage] = useState(0);
  const [fileUploadError, setFileUploadError] = useState(false)
  const [formData, setFormData] = useState({})



  useEffect (() => {
    if(file){
      handleFileUpload(file);
    }
  }, [file]);

  const handleFileUpload = (file) =>{
    const storage = getStorage(app);
    const fileName = new Date().getTime()+ file.name;
    const storageRef = ref(storage, fileName);
    const uploadTask = uploadBytesResumable(storageRef, file);

    uploadTask.on('state_changed', 
      (snapshot) =>{
        const progress = (snapshot.bytesTransferred / snapshot.totalBytes) * 100;
        setFilePercentage(Math.round(progress));
      },
    
    (error) => {
      setFileUploadError(true);
    },
    () => {
      getDownloadURL(uploadTask.snapshot.ref).then((downloadURL) => setFormData({...formData, avatar: downloadURL}));
    }
    )
  };


  return (
    <div className='max-w-lg p-3 mx-auto'>
      <h1 className="text-2xl uppercase text-center text-blue-900 font-serif my-10 tracking-wide">Profile</h1>
      <form className='flex flex-col gap-4'> 
      <input onChange={(e) => setFile(e.target.files[0])} type="file" ref={fileRef} hidden accept='image/*'/>
        <img onClick={() => fileRef.current.click()} src={formData.avatar || currentUser.avatar} alt="" className='rounded-full h-24 w-24 object-cover self-center mt-2 cursor-pointer bg-blue-100'/>
        <p className='text-sm self-center'>
          {
            fileUploadError ? (<span className='text-red-700'>Error image upload (image must be less than 2 mb) </span>) :
            filePercentage > 0 && filePercentage < 100 ? (<span className='text-blue-900'>{`Uploading ${filePercentage}%`}</span>) :
            filePercentage === 100 ? (<span className='text-green-900'>Image successfully uploaded</span>) : ("")
          }
        </p>
        <input type="text" placeholder='Username' id='username' className='border p-2 rounded-md text-sm'/>
        <input type="email" placeholder='Email' id='email' className='border p-2 rounded-md text-sm'/>
        <input type="password" placeholder='Password' id='password' className='border p-2 rounded-md text-sm'/>
        <button className='bg-blue-950 text-white text-sm p-2 rounded-md uppercase hover:opacity-90 disabled:opacity-80'>Update</button>
      </form>
      <div className='flex justify-between mt-4'>
        <span className='text-red-700 cursor-pointer'>Delete Account</span>
        <span className='text-red-700 cursor-pointer'>Log Out</span>
      </div>
    </div>
  )
}
