import { useEffect, useState, useRef } from "react" import { useNavigate } from "react-router-dom" import { useTranslation } from "../hooks/useTranslation" import { getUserProfile, updateUserProfile, updateProfilePicture, removeProfilePicture } from "../api/users" import { Button } from "../components/ui/button" import { Camera, Edit2, Trash2, User as UserIcon, UploadCloud, X, Check } from "lucide-react" import JalaliDatePicker from "../components/ui/JalaliDatePicker" import { toast } from "sonner" import { Modal } from "../components/Modal" export interface UserProfile { id?: string; email?: string; mobile?: string; first_name?: string; last_name?: string; full_name?: string; description?: string; birth_date?: string; age?: number; profile_picture?: string; created_at?: string; } export default function Profile() { const navigate = useNavigate() const [user, setUser] = useState(null) const [isLoading, setIsLoading] = useState(true) const { t, lang } = useTranslation() const isFa = lang === 'fa' const toPersianNum = (num: string | number | undefined | null) => { if (num === null || num === undefined) return num if (!isFa) return num return num.toString().replace(/\d/g, d => '۰۱۲۳۴۵۶۷۸۹'[d as any]) } const formatDate = (dateStr: string | undefined) => { if (!dateStr) return "-" try { const date = new Date(dateStr) return new Intl.DateTimeFormat(isFa ? 'fa-IR' : 'en-US', { dateStyle: 'long', timeZone: 'Asia/Tehran' }).format(date) } catch (e) { return dateStr } } // Modals & Editing state const [isEditing, setIsEditing] = useState(false) const [isPicModalOpen, setIsPicModalOpen] = useState(false) const [isSaving, setIsSaving] = useState(false) // Form states const [formData, setFormData] = useState>({}) const [selectedFile, setSelectedFile] = useState(null) const [dragActive, setDragActive] = useState(false) const fileInputRef = useRef(null) const fetchProfile = async () => { try { const data = await getUserProfile() setUser(data) } catch (error) { navigate("/auth") } finally { setIsLoading(false) } } useEffect(() => { fetchProfile() }, []) const handleEditClick = () => { if (user) { setFormData({ first_name: user.first_name || "", last_name: user.last_name || "", email: user.email || "", description: user.description || "", birth_date: user.birth_date || "", }) setIsEditing(true) } } const handleCancelEdit = () => { setIsEditing(false) setFormData({}) } const handleSaveProfile = async () => { setIsSaving(true) try { const payload: Record = {} Object.entries(formData).forEach(([key, value]) => { if (key === "birth_date" && value === "") { payload[key] = null } else if (value !== undefined && value !== null) { payload[key] = value } }) const updatedUser = await updateUserProfile(payload) setUser(prev => prev ? { ...prev, ...updatedUser } : updatedUser) setIsEditing(false) toast.success(t.profile.toasts.successEdit) } catch (error) { toast.error(t.profile.toasts.error) console.error("Failed to update profile", error) } finally { setIsSaving(false) } } const handlePictureUpload = async () => { if (!selectedFile) return setIsSaving(true) try { const response = await updateProfilePicture(selectedFile) setUser(prev => prev ? { ...prev, profile_picture: response.profile_picture } : response) setIsPicModalOpen(false) setSelectedFile(null) toast.success(t.profile.toasts.successImage) } catch (error) { toast.error(t.profile.toasts.error) console.error("Failed to upload picture", error) } finally { setIsSaving(false) } } const handleDeletePicture = async () => { setIsSaving(true) try { const response = await removeProfilePicture() setUser(prev => prev ? { ...prev, profile_picture: response.profile_picture || null } : response) setIsPicModalOpen(false) toast.success(t.profile.toasts.successRemoveImage) } catch (error) { toast.error(t.profile.toasts.error) console.error("Failed to delete picture", error) } finally { setIsSaving(false) } } // Drag & Drop Handlers const handleDrag = (e: React.DragEvent) => { e.preventDefault() e.stopPropagation() if (e.type === "dragenter" || e.type === "dragover") { setDragActive(true) } else if (e.type === "dragleave") { setDragActive(false) } } const handleDrop = (e: React.DragEvent) => { e.preventDefault() e.stopPropagation() setDragActive(false) if (e.dataTransfer.files && e.dataTransfer.files[0]) { setSelectedFile(e.dataTransfer.files[0]) } } if (isLoading) { return ( <>
Loading...
) } if (!user) return null return ( <>
{/* Header Card */}
setIsPicModalOpen(true)}>
{user.profile_picture ? ( Profile ) : ( )}

{user.full_name || "-"}

{user.email || "-"}

{/* Details Card */}
{/* Header with Title and Edit Button */}

{t.profile?.title || 'Personal Information'}

{!isEditing && ( )}
{/* Row 1: First Name | Last Name */}
{t.profile?.firstName || 'First Name'} {isEditing ? ( setFormData({ ...formData, first_name: e.target.value })} disabled={isSaving} className="mt-1 w-full rounded-md border border-slate-300 bg-transparent px-3 py-2 text-sm dark:border-slate-700 dark:text-white focus:outline-none focus:ring-2 focus:ring-blue-500" /> ) : (

{user.first_name || "-"}

)}
{t.profile?.lastName || 'Last Name'} {isEditing ? ( setFormData({ ...formData, last_name: e.target.value })} disabled={isSaving} className="mt-1 w-full rounded-md border border-slate-300 bg-transparent px-3 py-2 text-sm dark:border-slate-700 dark:text-white focus:outline-none focus:ring-2 focus:ring-blue-500" /> ) : (

{user.last_name || "-"}

)}
{/* Row 2: Mobile | Email */}
{t.profile?.mobileNumber || 'Mobile'}

{toPersianNum(user.mobile)}

{t.profile?.email || 'Email'} {isEditing ? ( setFormData({ ...formData, email: e.target.value })} disabled={isSaving} dir="ltr" className="mt-1 w-full rounded-md border border-slate-300 bg-transparent px-3 py-2 text-sm dark:border-slate-700 dark:text-white focus:outline-none focus:ring-2 focus:ring-blue-500" /> ) : (

{user.email || "-"}

)}
{/* Row 3: Birth Date | Date Joined */}
{isEditing ? (
setFormData({ ...formData, birth_date: date })} disabled={isSaving} />
) : ( <> {t.profile?.birthDate || 'Birth Date'}

{formatDate(user.birth_date)} {user.age ? `(${toPersianNum(user.age)} ${t.profile?.yearsOld || 'years'})` : ""}

)}
{t.profile?.dateJoined || 'Date Joined'}

{formatDate(user.created_at)}

{/* Row 4: Description (Full Width) */}
{t.profile?.description || 'Description'} {isEditing ? (