import React, { useEffect, useRef } from 'react';

import { Avatar, Stack } from '@/mui/components';

function AvatarEdit(props) {
  const inputRef = useRef(null);

  const clearInput = () => {
    inputRef.current.value = '';
  };

  const readFile = () => {
    const [file] = inputRef.current.files;

    if (file) {
      const readerUrl = new FileReader();

      readerUrl.addEventListener('load', () => {
        // eslint-disable-next-line react/prop-types
        props.onChange(readerUrl.result);
      });

      readerUrl.addEventListener('error', () => {
        clearInput();
      });

      readerUrl.readAsDataURL(file);
    }
  };

  useEffect(() => {
    inputRef.current.click();
  }, []);

  return (
    <Stack
      component="label"
      spacing={0}
      alignItems="center"
      justifyContent="center"
      style={{
        // eslint-disable-next-line react/prop-types
        minHeight: props.rowHeight,
      }}
    >
      <Avatar
        // eslint-disable-next-line react/prop-types
        size={props.size}
        // eslint-disable-next-line react/prop-types
        src={props.value}
        onClick={() => null}
      />
      <input
        // eslint-disable-next-line react/prop-types
        {...props.overrideProps.root}
        ref={inputRef}
        type="file"
        hidden
        onChange={readFile}
      />
    </Stack>
  );
}

export default AvatarEdit;
