import React, { FC, useRef } from "react";
import Button from "./Button";
import DefaultImg from "../assets/icons/no-user.svg";

export type AvatarProps = {
  id: string;
  name?: string;
  value: string;
  onChange?: (base64: string) => void;
};

const Avatar: FC<AvatarProps> = ({ id, name, value, onChange }) => {
  function fileChangedHandler(e: React.ChangeEvent<HTMLInputElement>) {
    const fileList = e.target.files;

    if (!fileList) return;
    const file = fileList[0];

    const reader = new FileReader();

    // Convert the file to base64 text
    if (file && file.type.match("image.*")) {
      reader.readAsDataURL(file);
    }

    reader.onloadend = () => {
      const base64 = reader.result;

      if (typeof base64 === "string") {
        if (onChange) onChange(base64);
      }
    };
  }

  const inputRef = useRef<HTMLInputElement>(null);

  const handleOpenFileInput = () => {
    if (inputRef.current) inputRef.current.click();
  };

  return (
    <div className="cols-grid grid-img">
      <div className="image-round">
        <img className="user-img" src={value ? value : DefaultImg} alt={name} />
        <label htmlFor={id} onClick={handleOpenFileInput}>
          <Button variant="secondary" label={"AGREGAR IMAGEN"} />
          {/*'Seleccione una imagen'*/}
        </label>
        <input
          style={{ display: "none" }}
          type="file"
          id={id}
          ref={inputRef}
          name={name}
          onChange={fileChangedHandler}
        />
      </div>
    </div>
  );
};

export default Avatar;
