import React, { useRef } from "react"; import { Menu, Box, Loader } from "@mantine/core"; import { useTranslation } from "react-i18next"; import { IconTrash, IconUpload } from "@tabler/icons-react"; import { CustomAvatar } from "@/components/ui/custom-avatar.tsx"; import { AvatarIconType } from "@/features/attachments/types/attachment.types.ts"; import { notifications } from "@mantine/notifications"; interface AvatarUploaderProps { currentImageUrl?: string | null; fallbackName?: string; radius?: string | number; size?: string | number; variant?: string; type: AvatarIconType; onUpload: (file: File) => Promise; onRemove: () => Promise; isLoading?: boolean; disabled?: boolean; } export default function AvatarUploader({ currentImageUrl, fallbackName, radius, variant, size, type, onUpload, onRemove, isLoading = false, disabled = false, }: AvatarUploaderProps) { const { t } = useTranslation(); const fileInputRef = useRef(null); const handleFileInputChange = async ( event: React.ChangeEvent, ) => { const file = event.target.files?.[0]; if (!file || disabled) { return; } // Validate file size (max 10MB) const maxSizeInBytes = 10 * 1024 * 1024; if (file.size > maxSizeInBytes) { notifications.show({ message: t("Image exceeds 10MB limit."), color: "red", }); // Reset the input if (fileInputRef.current) { fileInputRef.current.value = ""; } return; } try { await onUpload(file); } catch (error) { console.error(error); notifications.show({ message: t("Failed to upload image"), color: "red", }); } // Reset the input so the same file can be selected again if (fileInputRef.current) { fileInputRef.current.value = ""; } }; const handleUploadClick = () => { if (fileInputRef.current) { fileInputRef.current.click(); } else { console.error("File input ref is null!"); } }; const handleRemove = async () => { if (disabled) return; try { await onRemove(); notifications.show({ message: t("Image removed successfully"), }); } catch (error) { console.error(error); notifications.show({ message: t("Failed to remove image"), color: "red", }); } }; return ( {isLoading && ( )} } disabled={isLoading || disabled} onClick={handleUploadClick} > {t("Upload image")} {currentImageUrl && ( } color="red" onClick={handleRemove} disabled={isLoading || disabled} > {t("Remove image")} )} ); }