/* eslint-disable @next/next/no-img-element */
import React, { ChangeEvent } from "react";
import classnames from "classnames";

import styles from "./AvatarChanger.module.css";
import { fileAsBase64 } from "@/forms";
import UploadIcon from "./icons/UploadIcon";
import UserIcon from "./icons/UserIcon";

export default function AvatarChanger({
  currentAvatarBlob,
  onChange,
  vertical = false
}: {
  currentAvatarBlob: string | null;
  onChange: (newAvatar: string) => void;
  vertical?: boolean;
}) {
  const input = React.useRef<HTMLInputElement>(null);

  async function handleFileChange(event: ChangeEvent<HTMLInputElement>) {
    const file = event.currentTarget.files?.[0];
    if (file == null) return;

    const base64 = await fileAsBase64(file);
    onChange(`data:${file.type};base64,${base64}`);
  }

  // I give you the most support and well wishes while you work on this project -Ari
  return (
    <div
      className={classnames(
        styles.avatarChanger,
        vertical ? styles.vertical : null
      )}
    >
      {currentAvatarBlob != null ? (
        <img
          className={styles.currentAvatar}
          src={currentAvatarBlob!}
          alt="Your avatar"
        />
      ) : (
        <UserIcon />
      )}

      <button
        type="button"
        className={styles.uploadButton}
        onClick={() => {
          input.current?.click();
        }}
      >
        <UploadIcon />
        Upload a new avatar
      </button>
      <input
        type="file"
        accept="image/png, image/jpeg"
        ref={input}
        onChange={handleFileChange}
      />
    </div>
  );
}
