import { useState, useCallback } from 'react'; import { useAuth } from '@/contexts/AuthContext'; import { supabase } from '@/integrations/supabase/client'; import { toast } from 'sonner'; export interface ProfileUpdateData { display_name?: string; bio?: string; avatar_url?: string; } export const useProfileUpdate = () => { const { user, refreshProfile } = useAuth(); const [isLoading, setIsLoading] = useState(false); const [error, setError] = useState(null); const updateProfile = useCallback(async (updates: ProfileUpdateData) => { if (!user) { setError('يجب تسجيل الدخول أولاً'); return false; } setIsLoading(true); setError(null); try { if (updates.display_name && updates.display_name.trim().length < 2) { throw new Error('اسم العرض يجب أن يكون 2 أحرف على الأقل'); } if (updates.bio && updates.bio.trim().length > 500) { throw new Error('النبذة التعريفية يجب أن تكون أقل من 500 حرف'); } const { error: supabaseError } = await supabase .from('profiles') .update({ display_name: updates.display_name?.trim(), bio: updates.bio?.trim(), avatar_url: updates.avatar_url, updated_at: new Date().toISOString(), }) .eq('user_id', user.id); if (supabaseError) throw supabaseError; await refreshProfile(); toast.success('تم تحديث الملف الشخصي بنجاح ✓'); return true; } catch (err: any) { const errorMessage = err.message || 'حدث خطأ أثناء تحديث الملف الشخصي'; setError(errorMessage); toast.error(errorMessage); return false; } finally { setIsLoading(false); } }, [user, refreshProfile]); const updateAvatar = useCallback(async (avatarUrl: string) => { return updateProfile({ avatar_url: avatarUrl }); }, [updateProfile]); const updateBio = useCallback(async (bio: string) => { return updateProfile({ bio }); }, [updateProfile]); const updateDisplayName = useCallback(async (displayName: string) => { return updateProfile({ display_name: displayName }); }, [updateProfile]); return { isLoading, error, updateProfile, updateAvatar, updateBio, updateDisplayName, }; };