/**
 * This file is part of the SplendidBear Websites' projects.
 *
 * Copyright (c) 2026 @ www.splendidbear.org
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

import React, { useMemo, useRef } from 'react';
import { string } from 'prop-types';
import { useProfileDataProvider } from '@mine-hooks/useGameDataProvider';

export const AvatarUpload = ({ uploadUrl, initialThumbUrl, initials }) => {
  const inputRef = useRef(null);
  const [thumbUrl, setThumbUrl] = React.useState(initialThumbUrl || null);
  const { uploadAvatarMutation: { isPending, error, mutate } } = useProfileDataProvider();

  const handleChange = e => {
    const file = e.target.files?.[0];
    if (!file) return;

    mutate({ uploadUrl, file }, {
      onSuccess: data => {
        setThumbUrl(data.thumbUrl);

        const navImg = document.querySelector('.hero-auth-avatar:not(.hero-auth-avatar--initials)');
        const navInitials = document.querySelector('.hero-auth-avatar.hero-auth-avatar--initials');

        if (navImg) {
          navImg.src = data.thumbUrl;
        } else if (navInitials) {
          const img = document.createElement('img');
          img.src = data.thumbUrl;
          img.alt = navInitials.textContent.trim();
          img.className = 'hero-auth-avatar';
          navInitials.replaceWith(img);
        }
      },
    });
  };

  const errorMessage = useMemo(() => error?.message ?? null, [error]);

  return (
    <div
      className={`profile-avatar${isPending ? ' profile-avatar--loading' : ''}`}
      title="Click to change profile picture"
      onClick={() => inputRef.current?.click()}
    >
      {thumbUrl
        ? <img src={thumbUrl} alt={initials} className="profile-avatar__img" />
        : <span className="profile-avatar__initials">{initials}</span>
      }
      <div className="profile-avatar__overlay">
        <i className="fa fa-camera" />
      </div>
      <input
        ref={inputRef}
        type="file"
        accept="image/jpeg,image/png,image/gif,image/webp"
        style={{ display: 'none' }}
        onChange={handleChange}
      />
      {errorMessage && <div className="profile-avatar__error">{errorMessage}</div>}
    </div>
  );
}

AvatarUpload.propTypes = {
  uploadUrl: string.isRequired,
  initialThumbUrl: string,
  initials: string.isRequired,
};
