"use client" import { useState, useRef } from "react" import { Loader2, Camera, Upload, Trash2 } from "lucide-react" import { toast } from "sonner" import { Session } from "next-auth" import { Button } from "@/components/ui/button" import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card" import { Avatar, AvatarImage, AvatarFallback } from "@/components/ui/avatar" interface ProfileImageProps { user: { name?: string | null image?: string | null } update: (data?: { name?: string | null; email?: string | null; image?: string | null }) => Promise } export function ProfileImage({ user, update }: ProfileImageProps) { const fileInputRef = useRef(null) const [isImageLoading, setIsImageLoading] = useState(false) const [profileImageUrl, setProfileImageUrl] = useState(user.image || null) const handleImageUpload = async (event: React.ChangeEvent) => { const file = event.target.files?.[0] if (!file) return setIsImageLoading(true) try { const formData = new FormData() formData.append('image', file) const response = await fetch('/api/user/profile-image', { method: 'POST', body: formData, }) const result = await response.json() if (!response.ok) { toast.error(result.error || 'Failed to upload image') return } setProfileImageUrl(result.profileImage.url) toast.success('Profile image uploaded successfully!') await update({ image: result.profileImage.url }) } catch { toast.error('An unexpected error occurred') } finally { setIsImageLoading(false) if (fileInputRef.current) { fileInputRef.current.value = '' } } } const handleImageDelete = async () => { setIsImageLoading(true) try { const response = await fetch('/api/user/profile-image', { method: 'DELETE', }) const result = await response.json() if (!response.ok) { toast.error(result.error || 'Failed to delete image') return } setProfileImageUrl(null) toast.success('Profile image deleted successfully!') await update({ image: null }) } catch { toast.error('An unexpected error occurred') } finally { setIsImageLoading(false) } } return ( Profile Image Upload or update your profile picture
{user.name?.charAt(0)?.toUpperCase() || 'U'}
{profileImageUrl && ( )}

Supported formats: JPEG, PNG, WebP, GIF. Maximum size: 10MB.

) }