"use client"; import { useState, useRef, useEffect } from "react"; import Image from "next/image"; import { UserMetaCardProps } from "@/interface/user"; import { uploadMedia } from "@/service/mediaService"; import { toast } from "sonner"; import { apiUpdateUser } from "@/service/userService"; import { URL_MEDIA } from "../../../api"; import { useRouter } from "next/navigation"; export default function UserMetaCard({ data }: { data: UserMetaCardProps }) { const currentAvatar = data.data?.profile?.avatar_url || "/images/no-images.jpg"; const [previewImage, setPreviewImage] = useState(currentAvatar); const [isUploading, setIsUploading] = useState(false); const fileInputRef = useRef(null); const router = useRouter(); useEffect(() => { if (data.data?.profile?.avatar_url) { setPreviewImage(data.data.profile.avatar_url); } }, [data.data?.profile?.avatar_url]); const handleAvatarClick = () => { if (!isUploading) { fileInputRef.current?.click(); } }; const handleFileChange = async ( event: React.ChangeEvent, ) => { const file = event.target.files?.[0]; if (!file) return; const objectUrl = URL.createObjectURL(file); const backupImage = previewImage; setPreviewImage(objectUrl); try { setIsUploading(true); const uploadedMedia = await uploadMedia(file); // console.log("Upload thành công:", uploadedMedia); if (uploadedMedia?.storage_key) { const url = URL_MEDIA + uploadedMedia.storage_key; setPreviewImage(url); if (data.data) { try { await apiUpdateUser({ avatar_url: url }); window.location.href = window.location.pathname; toast.success("Cập nhật avatar thành công!"); } catch (error) { console.error("Lỗi khi cập nhật avatar:", error); toast.warning("Lỗi khi cập nhật ảnh đại diện. Vui lòng thử lại!"); } } } } catch (error) { console.error("Lỗi khi upload avatar:", error); setPreviewImage(backupImage); alert("Không thể tải ảnh lên. Vui lòng thử lại!"); } finally { setIsUploading(false); if (fileInputRef.current) { fileInputRef.current.value = ""; } } }; return (
avatar
{isUploading ? ( ) : ( )}

{data.data?.profile?.display_name || "Full Name"}

{data.data?.roles?.map((role) => role.name).join(", ") || "No roles available"}

{data.data?.profile?.bio && ( <>

{data.data.profile.bio}

)}
); }