import React, { useCallback, useEffect, useRef, useState } from "react";
import PropTypes from "prop-types";
import {
  AddFile,
  AddIcon,
  ImageOverlay,
  ImagePickerContainer,
  ImageUploaded,
  Tools,
} from "./ImagePicker.styled";
import { IconButton } from "../Buttons/IconButton/IconButton";
import { ReactComponent as EditIcon } from "../../assets/images/svg/edit.svg";
import { ReactComponent as TrashIcon } from "../../assets/images/svg/trash.svg";

const ImagePicker = (props) => {
  const fileInputRef = useRef(null);
  const imageRef = useRef(null);
  const [image, setImage] = useState("");
  const [isEditing, setIsEditing] = useState(false);

  useEffect(() => {
    if (props.image)
      setImage(props.image);
  }, [props.image]);

  let listener = useCallback((event) => {
    if (imageRef.current) {
      if (imageRef.current.contains(event.target)) {
        setIsEditing(true);
      } else {
        setIsEditing(false);
      }
    }
  }, [imageRef.current])
  useEffect(() => {
    window.addEventListener("click", listener);
    return () => window.removeEventListener("click", listener);
  }, []);
  const handleChange = () => {
    fileInputRef.current.value = "";
    fileInputRef.current.click();
  };
  const handleImage = (event) => {
    let reader = new FileReader();
    reader.readAsDataURL(event.target.files[0]);
    reader.onload = () => {
      if (props.setImage) props.setImage(reader.result);
      setImage(reader.result);
    };
    reader.onerror = (error) => {
      console.log(error);
    };
  };
  const handleDelete = () => {
    if (props.deleteImage) props.deleteImage();
    setImage("");
    setIsEditing(false);
  };
  return (
    <ImagePickerContainer
      className={props.className}
      onClick={!image ? handleChange : () => {}}
      hasImage={props.image}
    >
      <AddFile type="file" ref={fileInputRef} onInput={handleImage} accept=".jpg, .jpeg, .png" />
      {image ? (
        <React.Fragment>
          <ImageUploaded src={image} draggable={false} ref={imageRef} />
          {isEditing && (
            <React.Fragment>
              <ImageOverlay />
              <Tools showDeleteIcon={props.showDeleteIcon}>
                <IconButton onClick={handleChange}>
                  <EditIcon />
                </IconButton>
                {props.showDeleteIcon && (
                  <IconButton onClick={handleDelete}>
                    <TrashIcon />
                  </IconButton>
                )}
              </Tools>
            </React.Fragment>
          )}
        </React.Fragment>
      ) : (
        <AddIcon />
      )}
      {props.children}
    </ImagePickerContainer>
  );
};
ImagePicker.propTypes = {
  children: PropTypes.node,
  className: PropTypes.string,
  setImage: PropTypes.func,
  image: PropTypes.func,
  deleteImage: PropTypes.func,
  showDeleteIcon: PropTypes.bool,
};
export default ImagePicker;
