/* eslint-disable react/prop-types */
import React, { useEffect, useRef } from 'react';

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

function Edit(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', () => {
        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={{
        minHeight: props.rowHeight,
      }}
    >
      <Avatar size={props.size} src={props.value} onClick={() => null} />
      <input {...props.overrideProps.root} ref={inputRef} type="file" hidden onChange={readFile} />
    </Stack>
  );
}

export default Edit;
