All files / app/(auth) add-loved-one.tsx

0% Statements 0/54
0% Branches 0/38
0% Functions 0/8
0% Lines 0/54

Press n or j to go to the next uncovered block, b, p or k for the previous block.

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 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                             
import React, { useState } from 'react';
import {
  View,
  Text,
  StyleSheet,
  KeyboardAvoidingView,
  Platform,
  ScrollView,
  TouchableOpacity,
  TextInput,
  Image,
  Alert,
} from 'react-native';
import { SafeAreaView } from 'react-native-safe-area-context';
import { router, useLocalSearchParams } from 'expo-router';
import { Ionicons } from '@expo/vector-icons';
import * as ImagePicker from 'expo-image-picker';
import { Button } from '@/components/ui/Button';
import { ErrorMessage } from '@/components/ui/ErrorMessage';
import { AppColors, FontSizes, Spacing, BorderRadius, FontWeights } from '@/constants/theme';
import { api } from '@/services/api';
 
export default function AddLovedOneScreen() {
  const params = useLocalSearchParams<{ email: string; inviteCode: string }>();
  const inviteCode = params.inviteCode || '';
 
  const [name, setName] = useState('');
  const [address, setAddress] = useState('');
  const [avatarUri, setAvatarUri] = useState<string | null>(null);
  const [isLoading, setIsLoading] = useState(false);
  const [error, setError] = useState<string | null>(null);
 
  const handlePickAvatar = async () => {
    const { status } = await ImagePicker.requestMediaLibraryPermissionsAsync();
    if (status !== 'granted') {
      Alert.alert('Permission needed', 'Please allow access to your photo library.');
      return;
    }
 
    const result = await ImagePicker.launchImageLibraryAsync({
      mediaTypes: ['images'],
      allowsEditing: true,
      aspect: [1, 1],
      quality: 0.5,
    });
 
    if (!result.canceled && result.assets[0]) {
      setAvatarUri(result.assets[0].uri);
    }
  };
 
  const handleTakePhoto = async () => {
    const { status } = await ImagePicker.requestCameraPermissionsAsync();
    if (status !== 'granted') {
      Alert.alert('Permission needed', 'Please allow access to your camera.');
      return;
    }
 
    const result = await ImagePicker.launchCameraAsync({
      allowsEditing: true,
      aspect: [1, 1],
      quality: 0.5,
    });
 
    if (!result.canceled && result.assets[0]) {
      setAvatarUri(result.assets[0].uri);
    }
  };
 
  const handleAvatarPress = () => {
    Alert.alert(
      'Add Photo',
      'Choose how to add a photo',
      [
        { text: 'Take Photo', onPress: handleTakePhoto },
        { text: 'Choose from Library', onPress: handlePickAvatar },
        { text: 'Cancel', style: 'cancel' },
      ]
    );
  };
 
  const handleContinue = async () => {
    setError(null);
 
    const trimmedName = name.trim();
 
    if (!trimmedName) {
      setError('Please enter the name of your loved one');
      return;
    }
 
    setIsLoading(true);
 
    try {
      // Create beneficiary on server IMMEDIATELY
      const trimmedAddress = address.trim();
      const result = await api.createBeneficiary({
        name: trimmedName,
        address: trimmedAddress || undefined,
      });
 
      if (!result.ok || !result.data) {
        setError(result.error?.message || 'Failed to create beneficiary');
        return;
      }
 
      const beneficiaryId = result.data.id;
 
      // Upload avatar if selected
      if (avatarUri) {
        const avatarResult = await api.updateBeneficiaryAvatar(beneficiaryId, avatarUri);
        if (!avatarResult.ok) {
          // Continue anyway - avatar is not critical
        }
      }
 
      // Navigate to the purchase/subscription screen with beneficiary ID
      router.replace({
        pathname: '/(auth)/purchase',
        params: {
          beneficiaryId: String(beneficiaryId),
          lovedOneName: trimmedName,
          lovedOneAddress: address.trim(),
          inviteCode,
        },
      });
    } catch (err) {
      setError(err instanceof Error ? err.message : 'Something went wrong');
    } finally {
      setIsLoading(false);
    }
  };
 
  const handleSkip = async () => {
    // Mark onboarding as completed so we don't redirect back here
    await api.setOnboardingCompleted(true);
    // Skip and go to main app without adding loved one
    router.replace('/(tabs)');
  };
 
  const nameInitial = name.trim() ? name.trim().charAt(0).toUpperCase() : '+';
 
  return (
    <SafeAreaView style={styles.container} edges={['top', 'bottom']}>
      <KeyboardAvoidingView
        style={styles.keyboardView}
        behavior={Platform.OS === 'ios' ? 'padding' : 'height'}
      >
        <ScrollView
          contentContainerStyle={styles.scrollContent}
          keyboardShouldPersistTaps="handled"
          showsVerticalScrollIndicator={false}
        >
          {/* Header */}
          <View style={styles.header}>
            <Text style={styles.title}>Add a Loved One</Text>
            <Text style={styles.subtitle}>
              Tell us about the person you want to care for
            </Text>
          </View>
 
          {/* Error Message */}
          {error && (
            <ErrorMessage
              message={error}
              onDismiss={() => setError(null)}
            />
          )}
 
          {/* Avatar Section */}
          <TouchableOpacity style={styles.avatarSection} onPress={handleAvatarPress}>
            <View style={styles.avatarContainer}>
              {avatarUri ? (
                <Image source={{ uri: avatarUri }} style={styles.avatarImage} />
              ) : (
                <Text style={styles.avatarText}>{nameInitial}</Text>
              )}
              <View style={styles.avatarEditBadge}>
                <Ionicons name="camera" size={18} color={AppColors.white} />
              </View>
            </View>
            <Text style={styles.avatarHint}>Tap to add photo</Text>
          </TouchableOpacity>
 
          {/* Form */}
          <View style={styles.form}>
            <View style={styles.inputGroup}>
              <Text style={styles.inputLabel}>Name *</Text>
              <View style={styles.inputContainer}>
                <Ionicons name="person-outline" size={20} color={AppColors.textMuted} />
                <TextInput
                  style={styles.input}
                  value={name}
                  onChangeText={(text) => {
                    setName(text);
                    setError(null);
                  }}
                  placeholder="e.g., Grandma Julia"
                  placeholderTextColor={AppColors.textMuted}
                  autoCapitalize="words"
                  autoCorrect={false}
                  editable={!isLoading}
                />
              </View>
            </View>
 
            <View style={styles.inputGroup}>
              <Text style={styles.inputLabel}>Address (optional)</Text>
              <View style={styles.inputContainer}>
                <Ionicons name="location-outline" size={20} color={AppColors.textMuted} />
                <TextInput
                  style={styles.input}
                  value={address}
                  onChangeText={setAddress}
                  placeholder="123 Main St, City, State"
                  placeholderTextColor={AppColors.textMuted}
                  editable={!isLoading}
                />
              </View>
            </View>
          </View>
 
          {/* Continue Button */}
          <View style={styles.buttonContainer}>
            <Button
              title="Continue"
              onPress={handleContinue}
              loading={isLoading}
              fullWidth
              size="lg"
            />
          </View>
 
          {/* Info */}
          <View style={styles.infoContainer}>
            <Text style={styles.infoText}>
              You'll be able to add more loved ones later and invite family members to help care for them
            </Text>
          </View>
 
          {/* Skip Button */}
          <TouchableOpacity style={styles.skipButton} onPress={handleSkip}>
            <Text style={styles.skipText}>Skip for now</Text>
          </TouchableOpacity>
        </ScrollView>
      </KeyboardAvoidingView>
    </SafeAreaView>
  );
}
 
const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: AppColors.background,
  },
  keyboardView: {
    flex: 1,
  },
  scrollContent: {
    flexGrow: 1,
    paddingHorizontal: Spacing.lg,
    paddingTop: Spacing.xl,
    paddingBottom: Spacing.lg,
  },
  header: {
    alignItems: 'center',
    marginBottom: Spacing.xl,
  },
  title: {
    fontSize: FontSizes['2xl'],
    fontWeight: FontWeights.bold,
    color: AppColors.textPrimary,
    marginBottom: Spacing.md,
    textAlign: 'center',
  },
  subtitle: {
    fontSize: FontSizes.base,
    color: AppColors.textSecondary,
    textAlign: 'center',
  },
  avatarSection: {
    alignItems: 'center',
    marginBottom: Spacing.xl,
  },
  avatarContainer: {
    width: 120,
    height: 120,
    borderRadius: 60,
    backgroundColor: AppColors.primaryLight,
    justifyContent: 'center',
    alignItems: 'center',
    position: 'relative',
  },
  avatarImage: {
    width: 120,
    height: 120,
    borderRadius: 60,
  },
  avatarText: {
    fontSize: FontSizes['3xl'],
    fontWeight: FontWeights.bold,
    color: AppColors.primary,
  },
  avatarEditBadge: {
    position: 'absolute',
    bottom: 4,
    right: 4,
    width: 36,
    height: 36,
    borderRadius: 18,
    backgroundColor: AppColors.primary,
    justifyContent: 'center',
    alignItems: 'center',
    borderWidth: 3,
    borderColor: AppColors.background,
  },
  avatarHint: {
    fontSize: FontSizes.sm,
    color: AppColors.textMuted,
    marginTop: Spacing.sm,
  },
  form: {
    marginBottom: Spacing.lg,
  },
  inputGroup: {
    marginBottom: Spacing.lg,
  },
  inputLabel: {
    fontSize: FontSizes.sm,
    fontWeight: FontWeights.medium,
    color: AppColors.textSecondary,
    marginBottom: Spacing.sm,
  },
  inputContainer: {
    flexDirection: 'row',
    alignItems: 'center',
    backgroundColor: AppColors.surface,
    borderRadius: BorderRadius.lg,
    paddingHorizontal: Spacing.md,
    borderWidth: 1,
    borderColor: AppColors.border,
  },
  input: {
    flex: 1,
    fontSize: FontSizes.base,
    color: AppColors.textPrimary,
    paddingVertical: Spacing.md,
    marginLeft: Spacing.sm,
  },
  buttonContainer: {
    marginTop: Spacing.md,
  },
  infoContainer: {
    alignItems: 'center',
    marginTop: Spacing.lg,
    paddingHorizontal: Spacing.md,
  },
  infoText: {
    fontSize: FontSizes.sm,
    color: AppColors.textMuted,
    textAlign: 'center',
    lineHeight: 20,
  },
  skipButton: {
    alignItems: 'center',
    paddingVertical: Spacing.lg,
    marginTop: Spacing.xl,
  },
  skipText: {
    fontSize: FontSizes.base,
    color: AppColors.textSecondary,
    textDecorationLine: 'underline',
  },
});