import React, { memo, useRef, useState } from 'react'
// import { useSelector } from 'react-redux';
import getImage from '../../utils/getImage';
import { useMutation, useQueryClient } from '@tanstack/react-query';
import { uploadProfileImg } from '../../services/services';
import queryKeys from '../../services/queryKeys';

const ProfileImage = memo(({intialData}) => {

    const queryClient = useQueryClient()

    const [selectedImg, setSelectedImg] = useState(null)
    
    // const {userDetails} = useSelector((state) => state?.userDetails); // CHECKS FOR ACTIVE USER DETAILS
    const avtarImage = "avtar/merms-user.png";

      // browser profile img
    const browserImg = useRef(null);
    const browseProfileImg = () => {
        browserImg.current.click();
    };

    const profileImgChangeHandler = (event) => {
        setSelectedImg(event.target.files[0])
    }

    const uploadProfileMutation = useMutation({
        mutationFn: (fields) => {
            if(!fields.img){
                throw new Error('Please, select an image')
            }
            return uploadProfileImg(fields)
        },
        onSuccess: (res) => {
            if(res.data.resultCode != '0'){
                throw({message: res?.data?.resultDescription ? res?.data?.resultDescription : 'An error occured'})
            }
            // const account_name = res?.data?.personal_data?.account_name
            // dispatch(updateUserDetails({ account_name }));
        },
        onSettled: ()=>{
            setTimeout(() => {
                queryClient.refetchQueries({
                    queryKey: [...queryKeys.profile_data], // type: 'active', // exact: true,
                })
                uploadProfileMutation.reset()
            }, 3000);
        }
    })

    const proceedToUpload = () => {
        let reqData = {
            token: localStorage.getItem('token'), // USER TOKEN
            uid: localStorage.getItem('uid'), // USER UID
            img: selectedImg
        }
        // console.log('reqData', reqData)
        uploadProfileMutation.mutate(reqData)
    }

      return (
            <div className="col-xl-3 pb-xl-0 pb-5 border-right">
                <div className="page-account-profil pt-5">
                    <div className="profile-img text-center rounded-circle">
                        <div className="pt-5">
                            <div className="bg-img m-auto">
                                <img 
                                    src={selectedImg ? URL.createObjectURL(selectedImg) : intialData?.personal_data?.picture ? intialData?.personal_data?.picture : getImage(avtarImage)}
                                    // src={getImage(avtarImage)}
                                    className="img-fluid" alt="user"
                                />
                                <input 
                                    ref={browserImg}
                                    className='d-none' 
                                    type='file' 
                                    accept="image/*"
                                    onChange={(e) => profileImgChangeHandler(e)}
                                    id='profile-image'
                                />
                            </div>
                            <div className="profile pt-4">
                                <h4 className="mb-1">{intialData?.personal_data?.lastname} {intialData?.personal_data?.firstname}</h4>
                                <div style={{padding: '10px'}}>
                                    <hr/>
                                </div>
                            </div>
                        </div>
                    </div>
    
                    <div className="profile-btn text-center">
                        <div>
                            <button onClick={browseProfileImg} className="btn btn-light text-primary mb-2">Change
                            </button>
                        </div>
                        {selectedImg &&
                        <div>
                            <button onClick={proceedToUpload} disabled={uploadProfileMutation.isSuccess || uploadProfileMutation.isPending} className="btn btn-light text-primary mb-2">
                                {uploadProfileMutation.isPaused ? 'Upload...' : 'Upload New Avatar'}
                            </button>
                        </div>
                        }
                        {/* success or error message */}
                        {(uploadProfileMutation.isSuccess || uploadProfileMutation.isError) &&
                        <div>
                            <p className={`${uploadProfileMutation.isSuccess ? 'text-success' : 'text-danger'}`}>
                                {uploadProfileMutation.isSuccess ? 'Uploaded successfully' : uploadProfileMutation.error.message}
                            </p>
                        </div>
                        }
                    </div>
                </div>
            </div>
      )
    }
)

export default ProfileImage
