aboutsummaryrefslogtreecommitdiff
path: root/src/screens/salary-screen.tsx
blob: 6847c4b8621537fe4667a683857477e4ad0f30e0 (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
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
import { useState } from 'react';
import {
    Alert,
    ScrollView,
    StyleSheet,
    Text,
    View,
} from 'react-native';
import Animated, { FadeInDown, LinearTransition } from 'react-native-reanimated';
import { useSafeAreaInsets } from 'react-native-safe-area-context';
import * as Haptics from 'expo-haptics';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Card, Divider, SectionLabel } from '@/components/ui/primitives';
import { useSalaryCalculator } from '@/hooks/use-app-hooks';
import { Colors, Spacing, Typography } from '@/constants/theme';
import { formatCurrency } from '@/utils/tax-calculator';
import { updateUserSalary } from '@/services/api';
import { useAuth } from '@/contexts/AuthContext';
import { useIsFocused } from "expo-router/react-navigation";

export default function SalaryScreen() {
    const insets = useSafeAreaInsets();
    const { user, updateUser } = useAuth();
    const isFocused = useIsFocused();

    const [grossStr, setGrossStr] = useState(user?.gross_salary ? String(user.gross_salary) : '');
    const [netOverrideStr, setNetOverrideStr] = useState(
        user?.net_salary_override ? String(user.net_salary_override) : ''
    );
    const [isOverriding, setIsOverriding] = useState(!!user?.net_salary_override);

    const result = useSalaryCalculator(grossStr);

    const effectiveNet = isOverriding
        ? parseFloat(netOverrideStr.replace(',', '.')) || 0
        : (result?.salarioLiquidoCalculado ?? 0);

    const [isSaving, setIsSaving] = useState(false);
    const [saved, setSaved] = useState(false);

    async function handleSave() {
        if (!result || !user) return;
        try {
            setIsSaving(true);
            setSaved(false);
            const updatedUser = await updateUserSalary(user.id, {
                gross_salary: result.salarioBruto,
                net_salary_override: isOverriding ? effectiveNet : null,
            });
            await updateUser(updatedUser);
            Haptics.notificationAsync(Haptics.NotificationFeedbackType.Success);
            setSaved(true);
            setTimeout(() => setSaved(false), 2500);
        } catch (err) {
            Alert.alert('Erro', 'Não foi possível salvar o salário.');
        } finally {
            setIsSaving(false);
        }
    }

    function handleToggleOverride() {
        if (isOverriding) {
            setNetOverrideStr('');
            setIsOverriding(false);
        } else {
            setNetOverrideStr(result?.salarioLiquidoCalculado.toFixed(2) ?? '');
            setIsOverriding(true);
        }
    }

    return (
        <View style={[styles.container, { paddingTop: insets.top }]}>
            {isFocused && (
                <ScrollView
                    contentContainerStyle={[
                        styles.scroll,
                        { paddingBottom: insets.bottom + Spacing.xxl },
                    ]}
                    keyboardShouldPersistTaps="handled"
                    showsVerticalScrollIndicator={false}
                >
                    <Animated.View entering={FadeInDown.duration(400)}>
                        <Text style={styles.title}>Meu Salário</Text>
                        <Text style={styles.subtitle}>
                            Informe seu salário bruto e ajuste o líquido se necessário.
                        </Text>
                    </Animated.View>

                    <Animated.View entering={FadeInDown.delay(100).duration(400)}>
                        <Input
                            id="salary-gross-input"
                            label="Salário Bruto"
                            prefix="R$"
                            value={grossStr}
                            onChangeText={setGrossStr}
                            keyboardType="decimal-pad"
                            placeholder="0,00"
                            hint="Valor antes dos descontos (INSS, IRRF)"
                        />
                    </Animated.View>

                    {result && (
                        <Animated.View entering={FadeInDown.delay(150).duration(400)} layout={LinearTransition.springify()}>
                            <Card style={styles.resultCard}>
                                <SectionLabel text="Cálculo Automático" />

                                <View style={styles.resultRow}>
                                    <Text style={styles.resultLabel}>Salário Bruto</Text>
                                    <Text style={[styles.resultValue, { color: Colors.textPrimary }]}>
                                        {formatCurrency(result.salarioBruto)}
                                    </Text>
                                </View>

                                <View style={styles.resultRow}>
                                    <Text style={styles.resultLabel}>Desconto INSS</Text>
                                    <Text style={[styles.resultValue, { color: Colors.negative }]}>
                                        - {formatCurrency(result.descontoINSS)}
                                    </Text>
                                </View>

                                <View style={styles.resultRow}>
                                    <Text style={styles.resultLabel}>Desconto IRRF</Text>
                                    <Text style={[styles.resultValue, { color: Colors.negative }]}>
                                        - {formatCurrency(result.descontoIRRF)}
                                    </Text>
                                </View>

                                <Divider />

                                <View style={styles.resultRow}>
                                    <Text style={[styles.resultLabel, { color: Colors.textPrimary }]}>
                                        Salário Líquido
                                    </Text>
                                    <Text style={[styles.resultValue, { color: Colors.positive }]}>
                                        {formatCurrency(result.salarioLiquidoCalculado)}
                                    </Text>
                                </View>
                            </Card>
                        </Animated.View>
                    )}

                    {result && (
                        <Animated.View
                            entering={FadeInDown.delay(200).duration(400)}
                            layout={LinearTransition.springify()}
                            style={styles.overrideSection}
                        >
                            <Button
                                label={
                                    isOverriding
                                        ? 'Usar valor calculado'
                                        : 'Tenho outros descontos (ajustar manualmente)'
                                }
                                variant="ghost"
                                onPress={handleToggleOverride}
                            />

                            {isOverriding && (
                                <Animated.View entering={FadeInDown.duration(300)}>
                                    <Input
                                        id="salary-net-override-input"
                                        label="Salário Líquido Real"
                                        prefix="R$"
                                        value={netOverrideStr}
                                        onChangeText={setNetOverrideStr}
                                        keyboardType="decimal-pad"
                                        placeholder="0,00"
                                        hint="Descontos extras: plano de saúde, VT, previdência privada, etc."
                                    />
                                </Animated.View>
                            )}
                        </Animated.View>
                    )}

                    {result && (
                        <Animated.View entering={FadeInDown.delay(300).duration(400)} layout={LinearTransition.springify()}>
                            <Button
                                id="salary-save-button"
                                label={saved ? 'Salvo com sucesso! ✓' : 'Salvar Salário'}
                                fullWidth
                                onPress={handleSave}
                                disabled={!result || isSaving || saved}
                                loading={isSaving}
                                style={saved ? { backgroundColor: Colors.positive } : undefined}
                            />
                        </Animated.View>
                    )}
                </ScrollView>
            )}
        </View>
    );
}

const styles = StyleSheet.create({
    container: {
        flex: 1,
        backgroundColor: Colors.background,
    },
    scroll: {
        padding: Spacing.md,
        gap: Spacing.lg,
    },
    title: {
        ...Typography.h1,
        color: Colors.textPrimary,
        marginBottom: Spacing.xs,
    },
    subtitle: {
        ...Typography.body,
        color: Colors.textSecondary,
    },
    resultCard: {
        gap: Spacing.sm,
    },
    resultRow: {
        flexDirection: 'row',
        justifyContent: 'space-between',
        alignItems: 'center',
    },
    resultLabel: {
        ...Typography.body,
        color: Colors.textSecondary,
    },
    resultValue: {
        ...Typography.body,
        fontFamily: 'DMSans_600SemiBold',
    },
    overrideSection: {
        gap: Spacing.md,
    },
});