"use client"

import type { IAvatarUploadProps } from "./AvatarUpload.d"
import type { JSX } from "react"

import cs from "classnames"
import { FunctionComponent, useRef, useState } from "react"

import { uploadFileWithProgress } from "@shared/api/uploadFile"
import { Avatar } from "@shared/ui/Avatar"

import styles from "./AvatarUpload.module.scss"

export const AvatarUpload: FunctionComponent<
	IAvatarUploadProps
> = ({ currentAvatarUrl, onAvatarChange, className }): JSX.Element => {
	const fileInputRef = useRef<HTMLInputElement>(null)
	const [uploadProgress, setUploadProgress] = useState<number | null>(null)

	const handleClick = () => {
		fileInputRef.current?.click()
	}

	const handleFileChange = async (
		e: React.ChangeEvent<HTMLInputElement>,
	) => {
		const file = e.target.files?.[0]
		if (!file) return

		setUploadProgress(0)
		try {
			const result = await uploadFileWithProgress(
				file,
				"avatars",
				setUploadProgress,
			)
			onAvatarChange(result.file_path)
		} catch (err) {
			console.error("Avatar upload failed:", err)
		} finally {
			setUploadProgress(null)
			if (fileInputRef.current) fileInputRef.current.value = ""
		}
	}

	return (
		<div
			className={cs(styles.root, className)}
			data-testid="AvatarUpload"
		>
			<button
				type="button"
				className={styles.avatarButton}
				onClick={handleClick}
				disabled={uploadProgress !== null}
			>
				<Avatar
					size="xlarge"
					url={currentAvatarUrl || ""}
				/>
			</button>
			<button
				type="button"
				className={styles.changeLink}
				onClick={handleClick}
				disabled={uploadProgress !== null}
			>
				{uploadProgress !== null
					? `Загрузка ${uploadProgress}%`
					: "Изменить фото"}
			</button>
			<input
				ref={fileInputRef}
				type="file"
				accept="image/*"
				className={styles.fileInput}
				onChange={handleFileChange}
			/>
		</div>
	)
}
