import React, { useEffect, useRef, useState } from 'react';
import { Avatar } from 'primereact/avatar';

const CustomAvatar = () => {
  const [image, setImage] = useState<string | ArrayBuffer | null>(null);
  const fileInputRef = useRef<HTMLInputElement>(null);

  const localStorageKey = 'userAvatarImage';

  const handleAvatarClick = () => {
    fileInputRef.current?.click();
  };
  
  const handleFileChange = (event: React.ChangeEvent<HTMLInputElement>) => {
    const file = event.target.files?.[0];
    if (file) {
      const reader = new FileReader();
      reader.onloadend = () => {
        const result = reader.result;
        setImage(result);
        if (typeof result === 'string') {
          localStorage.setItem(localStorageKey, result);
        }
      };
      reader.readAsDataURL(file);
    }
  };

  useEffect(() => {
    const savedImage = localStorage.getItem(localStorageKey);
    if (savedImage) {
      setImage(savedImage);
    }
  }, []);

  return (
    <div>
      <input
        ref={fileInputRef}
        type='file'
        accept='image/*'
        style={{ display: 'none' }}
        onChange={handleFileChange}
      />
      <Avatar
        className='p-overlay-badge'
        icon={!image ? 'pi pi-user' : undefined}
        image={typeof image === 'string' ? image : undefined}
        size='xlarge'
        onClick={handleAvatarClick}
        style={{
          cursor: 'pointer',
          boxShadow: '0px 4px 12px rgba(0, 0, 0, 0.2)',
        }}
      />
    </div>
  );
};

export default CustomAvatar;
