eletrotupi / tcc/ frontend/app/profile.tsx114be98ec7798e84a9f63b79b00cf224e5f3c8d8
6.8 KB | 267 lines Raw
1
import { useState, useEffect } from 'react';
2
import {
3
  View,
4
  StyleSheet,
5
  ScrollView,
6
  KeyboardAvoidingView,
7
} from 'react-native';
8

9
import { Text } from '@/components/ui/Text';
10
import { ThemedView } from '@/components/ui/themed-view'
11
import { Link, useLocalSearchParams, router } from 'expo-router';
12
import { StatusBar } from 'expo-status-bar';
13
import { SafeAreaView } from 'react-native-safe-area-context';
14
import { useThemeColor } from '@/hooks/use-theme-color';
15
import { Button, Input } from '@/components/ui';
16
import { useAuth } from '@/context/AuthContext';
17
import { apiClient, ApiError, User } from '@/lib/api'
18
import { useToast } from '@/context/ToastContext';
19
import { translateError, translateFields } from '@/lib/errors/translations';
20
import { Card } from '@/components/ui/Cards';
21
import AvatarUpload  from '@/components/ui/AvatarUpload';
22
import { Typography, Spacing, Colors } from '@/constants/theme';
23

24
export default function Profile() {
25
  const { user, updateAuthUser } = useAuth();
26
  const { showToast } = useToast();
27
  const [firstName, setFirstName] = useState(user.firstName);
28
  const [lastName, setLastName] = useState(user.lastName);
29
  const [email, setEmail] = useState(user.email);
30
  const [password, setPassword] = useState();
31
  const [confirmPassword, setConfirmPassword] = useState();
32
  const [loading, setLoading] = useState(false);
33
  const [errors, setErrors] = useState<{
34
    firstName?: string;
35
    password?: string;
36
    confirmPassword?: string;
37
  }>({});
38

39
  useEffect(() => {
40
    setFirstName(user.firstName)
41
    setLastName(user.lastName)
42
    setEmail(user.email)
43
  }, [user])
44

45
  const backgroundColor = useThemeColor({}, 'background');
46
  const textColor = useThemeColor({}, 'text');
47

48
  const validateForm = () => {
49
    const newErrors: {
50
      firstName?: string;
51
      email?: string;
52
      password?: string;
53
      confirmPassword?: string
54
    } = {};
55

56
    if (password) {
57
      if (!confirmPassword) {
58
        newErrors.confirmPassword = 'Precisa confirmar a senha';
59
      } else {
60
        if (password !== confirmPassword) {
61
          newErrors.confirmPassword = "Senhas não conferem";
62
        }
63
      }
64
    }
65

66
    if (!/\S+@\S+\.\S+/.test(email)) {
67
      newErrors.email = 'Por favor, use um email válido';
68
    }
69

70
    if (!firstName) {
71
      newErrors.firstName = 'É necessário ter um nome';
72
    }
73

74
    setErrors(newErrors);
75

76
    return Object.keys(newErrors).length === 0;
77
  }
78

79
  const handleUpdate = async () => {
80
    if (!validateForm()) return;
81

82
    const data = {};
83

84
    data.firstName = firstName
85
    data.lastName = lastName
86
    data.email = email
87

88
    if (password) {
89
      data.password = password
90
    }
91

92
    try {
93
      const id = user.id;
94

95
      const response = await apiClient.updateUser({
96
        id,
97
        firstName,
98
        lastName,
99
        email,
100
        password
101
      });
102

103
      updateAuthUser(response.user);
104

105
      router.replace('/(tabs)/insights');
106
    } catch (error: any) {
107
      console.error("[PROFILE]", error)
108
      if (error instanceof ApiError && error.fields) {
109
        setErrors(translateFields(error.fields));
110
      } else {
111
        showToast(translateError(error.message) || 'Falha ao atualizar o perfil', 'error');
112
      }
113
    }
114
  }
115

116
  const onChangeAvatar = (user: User) => {
117
    updateAuthUser(user);
118
  }
119

120
  return (
121
    <SafeAreaView style={[styles.container, { backgroundColor }]}>
122
      <StatusBar style={'dark'} />
123
      <KeyboardAvoidingView
124
        behavior='height'
125
        style={styles.keyboardView}
126
      >
127
        <ScrollView
128
          contentContainerStyle={styles.scrollContainer}
129
          showsVerticalScrollIndicator={false}
130
        >
131
          <AvatarUpload
132
            currentAvatar={user.avatarURL}
133
            onUploadSuccess={onChangeAvatar}
134
            onRemoveSuccess={onChangeAvatar} />
135

136
          <View style={styles.form}>
137
            <Card style={styles.cardBlock}>
138
              <Input
139
                label="Primeiro Nome"
140
                type="text"
141
                value={firstName}
142
                onChangeText={setFirstName}
143
                placeholder="Qual seu nome?"
144
                variant="darkGhost"
145
                error={errors.firstName}
146
              />
147

148
              <Input
149
                label="Sobrenome"
150
                type="text"
151
                value={lastName}
152
                variant="darkGhost"
153
                onChangeText={setLastName}
154
                placeholder="Qual seu sobrenome?"
155
                error={errors.lastName}
156
              />
157
            </Card>
158

159
            <Card style={styles.cardBlock}>
160
              <Input
161
                label="Email"
162
                type="text"
163
                value={email}
164
                variant="darkGhost"
165
                onChangeText={setEmail}
166
                placeholder="Qual seu email?"
167
                error={errors.email}
168
              />
169
            </Card>
170

171
            <Card style={styles.cardBlock}>
172
              <Input
173
                label="Nova senha"
174
                type="password"
175
                value={password}
176
                onChangeText={setPassword}
177
                placeholder="Digite uma nova senha"
178
                error={errors.password}
179
                variant="darkGhost"
180
                showPasswordToggle
181
              />
182

183
              <Input
184
                label="Confirmar nova senha"
185
                type="password"
186
                value={confirmPassword}
187
                onChangeText={setConfirmPassword}
188
                placeholder="Confirme a nova senha"
189
                error={errors.confirmPassword}
190
                variant="darkGhost"
191
                showPasswordToggle
192
              />
193

194
              <Text style={styles.cardBlockHint}>
195
                Preencha apenas se quiser mudar a sua senha
196
              </Text>
197
            </Card>
198

199
            <Button
200
              title="Atualizar perfil"
201
              onPress={handleUpdate}
202
              loading={loading}
203
              style={styles.resetButton}
204
            />
205
          </View>
206

207
        </ScrollView>
208
      </KeyboardAvoidingView>
209
    </SafeAreaView>
210
  )
211
}
212

213
const styles = StyleSheet.create({
214
  container: {
215
    flex: 1,
216
  },
217
  keyboardView: {
218
    flex: 1,
219
  },
220
  scrollContainer: {
221
    flexGrow: 1,
222
    paddingHorizontal: 24,
223
    justifyContent: 'start',
224
    minHeight: '100%',
225
  },
226
  header: {
227
    alignItems: 'left',
228
    marginBottom: 40,
229
  },
230
  title: {
231
    fontSize: 28,
232
    fontWeight: 'bold',
233
    marginBottom: 8,
234
  },
235
  subtitle: {
236
    fontSize: 16,
237
    textAlign: 'left',
238
  },
239
  form: {
240
    marginBottom: 32,
241
  },
242
  resetButton: {
243
    marginTop: 8,
244
  },
245
  link: {
246
    textAlign: 'center',
247
    fontSize: 14,
248
    fontWeight: '500',
249
  },
250
  footer: {
251
    flexDirection: 'row',
252
    justifyContent: 'center',
253
    alignItems: 'center',
254
    marginTop: 'auto',
255
    paddingBottom: 20,
256
  },
257
  footerText: {
258
    fontSize: 14,
259
  },
260
  cardBlock: {
261
    padding: Spacing.cardGap
262
  },
263
  cardBlockHint: {
264
    ...Typography.cardHint,
265
    color: Colors.light.textSecondary
266
  }
267
});