summaryrefslogtreecommitdiffstats
path: root/src/features/profile/hooks/useUpdateProfile.ts
blob: cd4a39a760f9178c2d5e7ad692a5842d88c3099f (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
// src/features/profile/hooks/useUpdateProfile.ts

import { useState } from 'react';
import { profileService } from '@/features/profile/services/profileService';
import { useAuthSession } from '@/providers/AuthProvider';
import { getErrorMessage } from '@/shared/lib/errors/getErrorMessage';

export function useUpdateProfile(initialDisplayName = '', initialPhotoURL = '') {
  const { user } = useAuthSession();

  const [displayName, setDisplayName] = useState(initialDisplayName);
  const [photoURL, setPhotoURL] = useState(initialPhotoURL);
  const [isSubmitting, setIsSubmitting] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const [successMessage, setSuccessMessage] = useState<string | null>(null);

  const submit = async () => {
    if (!user?.uid) {
      setError('No hay usuario autenticado');
      return;
    }

    if (!displayName.trim()) {
      setError('El nombre no puede estar vacío');
      return;
    }

    try {
      setError(null);
      setSuccessMessage(null);
      setIsSubmitting(true);

      await profileService.updateMyProfile({
        uid: user.uid,
        displayName: displayName.trim(),
        photoURL: photoURL.trim(),
      });

      setPhotoURL(photoURL.trim());
      setSuccessMessage('Perfil actualizado correctamente');
    } catch (err) {
      setError(getErrorMessage(err, 'No se pudo actualizar el perfil'));
    } finally {
      setIsSubmitting(false);
    }
  };

  return {
    displayName,
    photoURL,
    setDisplayName,
    setPhotoURL,
    isSubmitting,
    error,
    successMessage,
    submit,
  };
}