All files / src/views/profile EditProfileView.tsx

36.53% Statements 19/52
33.78% Branches 25/74
18.75% Functions 3/16
38% Lines 19/50

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 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 5581x 1x 1x                     1x 1x 1x             1x 2x 2x   2x                               2x                                                 2x 2x 2x 1x       2x                                                                                                                                                                                                                                                                                                                                                 4x 4x                                                                                                                                                                                                             1x                                                                                                                                                                                                                                                                                                                                                                                                                                    
import React, { useState, useCallback } from 'react';
import DateTimePicker from '@react-native-community/datetimepicker';
import {
  ActivityIndicator,
  KeyboardAvoidingView,
  Platform,
  ScrollView,
  StyleSheet,
  Text,
  TextInput,
  TouchableOpacity,
  View,
} from 'react-native';
import { router, type Href } from 'expo-router';
import { Ionicons, MaterialIcons } from '@expo/vector-icons';
import {
  useEditProfileViewModel,
  GENDER_OPTIONS,
  DISPLAY_NAME_MAX_LENGTH,
  BIO_MAX_LENGTH,
} from '@/viewmodels/profile/useEditProfileViewModel';
 
export default function EditProfileView() {
  const vm = useEditProfileViewModel();
  const [showDatePicker, setShowDatePicker] = useState(false);
 
  const getPickerDate = useCallback(() => {
    if (vm.formData.birthDate && vm.formData.birthDate.length === 10) {
      const parts = vm.formData.birthDate.split('.');
      if (parts.length === 3) {
        const d = parseInt(parts[0], 10);
        const m = parseInt(parts[1], 10) - 1;
        const y = parseInt(parts[2], 10);
        const parsed = new Date(y, m, d);
        if (!isNaN(parsed.getTime())) {
          return parsed;
        }
      }
    }
    return new Date();
  }, [vm.formData.birthDate]);
 
  const handleDateChange = useCallback(
    (event: any, selectedDate?: Date) => {
      if (Platform.OS === 'android') {
        setShowDatePicker(false);
      }
      if (!selectedDate || event.type === 'dismissed') return;
 
      const prevDate = getPickerDate();
      const onlyDayChanged =
        selectedDate.getDate() !== prevDate.getDate() &&
        selectedDate.getMonth() === prevDate.getMonth() &&
        selectedDate.getFullYear() === prevDate.getFullYear();
 
      const y = selectedDate.getFullYear();
      const m = String(selectedDate.getMonth() + 1).padStart(2, '0');
      const d = String(selectedDate.getDate()).padStart(2, '0');
      vm.updateField('birthDate', `${d}.${m}.${y}`);
 
      if (Platform.OS === 'ios' && (event.type === 'set' || onlyDayChanged)) {
        setShowDatePicker(false);
      }
    },
    [getPickerDate, vm],
  );
 
  const handleSave = async () => {
    const success = await vm.handleSave();
    if (success) {
      router.replace('/(tabs)/profile' as Href);
    }
  };
 
  return (
    <KeyboardAvoidingView
      style={styles.container}
      behavior={Platform.OS === 'ios' ? 'padding' : 'height'}
    >
      <ScrollView
        contentContainerStyle={styles.scrollContent}
        keyboardShouldPersistTaps="handled"
      >
        {/* Header */}
        <View style={styles.header}>
          <TouchableOpacity
            style={styles.backButton}
            onPress={() => router.back()}
            accessibilityRole="button"
            accessibilityLabel="Go back"
          >
            <MaterialIcons name="arrow-back" size={28} color="#111827" />
          </TouchableOpacity>
          <Text style={styles.screenTitle}>Edit Profile</Text>
          <View style={styles.headerSpacer} />
        </View>
 
        {/* Error Banner */}
        {vm.apiError ? (
          <View style={styles.errorBanner}>
            <Text style={styles.errorBannerText}>{vm.apiError}</Text>
          </View>
        ) : null}
 
        {/* Success Banner */}
        {vm.successMessage ? (
          <View style={styles.successBanner}>
            <Text style={styles.successBannerText}>{vm.successMessage}</Text>
          </View>
        ) : null}
 
        {/* Loading State */}
        {vm.isLoading ? (
          <View style={styles.loadingContainer}>
            <ActivityIndicator size="large" color="#0F172A" />
            <Text style={styles.loadingText}>Loading profile...</Text>
          </View>
        ) : (
          <View style={styles.formCard}>
            {/* Display Name */}
            <View style={styles.fieldGroup}>
              <Text style={styles.fieldLabel}>Display Name</Text>
              <TextInput
                style={[
                  styles.textInput,
                  vm.errors.displayName ? styles.textInputError : null,
                ]}
                value={vm.formData.displayName}
                onChangeText={(text) => vm.updateField('displayName', text)}
                placeholder="Enter your display name"
                placeholderTextColor="#9CA3AF"
                maxLength={DISPLAY_NAME_MAX_LENGTH}
                accessibilityLabel="Display name"
              />
              <Text style={styles.charCount}>
                {vm.formData.displayName.length}/{DISPLAY_NAME_MAX_LENGTH}
              </Text>
              {vm.errors.displayName ? (
                <Text style={styles.fieldError}>{vm.errors.displayName}</Text>
              ) : null}
            </View>
 
            {/* Bio */}
            <View style={styles.fieldGroup}>
              <Text style={styles.fieldLabel}>Bio</Text>
              <TextInput
                style={[
                  styles.textInput,
                  styles.textArea,
                  vm.errors.bio ? styles.textInputError : null,
                ]}
                value={vm.formData.bio}
                onChangeText={(text) => vm.updateField('bio', text)}
                placeholder="Tell us about yourself"
                placeholderTextColor="#9CA3AF"
                maxLength={BIO_MAX_LENGTH}
                multiline
                numberOfLines={4}
                textAlignVertical="top"
                accessibilityLabel="Bio"
              />
              <Text style={styles.charCount}>
                {vm.formData.bio.length}/{BIO_MAX_LENGTH}
              </Text>
              {vm.errors.bio ? (
                <Text style={styles.fieldError}>{vm.errors.bio}</Text>
              ) : null}
            </View>
 
            {/* Phone Number */}
            <View style={styles.fieldGroup}>
              <Text style={styles.fieldLabel}>Phone Number</Text>
              <TextInput
                style={[
                  styles.textInput,
                  vm.errors.phoneNumber ? styles.textInputError : null,
                ]}
                value={vm.formData.phoneNumber}
                onChangeText={(text) => vm.updateField('phoneNumber', text)}
                placeholder="+905551112233"
                placeholderTextColor="#9CA3AF"
                keyboardType="phone-pad"
                autoComplete="tel"
                textContentType="telephoneNumber"
                accessibilityLabel="Phone number"
              />
              {vm.errors.phoneNumber ? (
                <Text style={styles.fieldError}>{vm.errors.phoneNumber}</Text>
              ) : null}
            </View>
 
            <View style={styles.fieldGroup}>
              <Text style={styles.fieldLabel}>Default Location</Text>
              <View style={styles.locationInputRow}>
                <TextInput
                  style={styles.textInput}
                  value={vm.locationQuery}
                  onChangeText={vm.updateLocationQuery}
                  placeholder="Search for a place..."
                  placeholderTextColor="#9CA3AF"
                  accessibilityLabel="Default location"
                />
                {vm.formData.defaultLocationLat !== null ? (
                  <TouchableOpacity
                    style={styles.clearLocationBtn}
                    onPress={vm.clearLocation}
                    accessibilityRole="button"
                    accessibilityLabel="Clear default location"
                  >
                    <Text style={styles.clearLocationText}>X</Text>
                  </TouchableOpacity>
                ) : null}
              </View>
              {vm.isSearchingLocation ? (
                <ActivityIndicator
                  size="small"
                  color="#111827"
                  style={styles.searchSpinner}
                />
              ) : null}
              {vm.locationSuggestions.length > 0 ? (
                <View style={styles.suggestionsContainer}>
                  {vm.locationSuggestions.map((suggestion, index) => (
                    <TouchableOpacity
                      key={`${suggestion.lat}-${suggestion.lon}-${index}`}
                      style={styles.suggestionItem}
                      onPress={() => vm.selectLocationSuggestion(suggestion)}
                    >
                      <Text style={styles.suggestionText} numberOfLines={2}>
                        {suggestion.display_name}
                      </Text>
                    </TouchableOpacity>
                  ))}
                </View>
              ) : null}
            </View>
 
            {/* Gender */}
            {vm.canEditGender ? (
              <View style={styles.fieldGroup}>
                <Text style={styles.fieldLabel}>Gender</Text>
                <View style={styles.genderRow}>
                  {GENDER_OPTIONS.map((option) => {
                    const selected = vm.formData.gender === option.value;
                    return (
                      <TouchableOpacity
                        key={option.value}
                        style={[
                          styles.genderChip,
                          selected && styles.genderChipSelected,
                        ]}
                        onPress={() =>
                          vm.updateField(
                            'gender',
                            selected ? '' : option.value,
                          )
                        }
                        accessibilityRole="button"
                        accessibilityLabel={`Select ${option.label}`}
                      >
                        <Text
                          style={[
                            styles.genderChipText,
                            selected && styles.genderChipTextSelected,
                          ]}
                        >
                          {option.label}
                        </Text>
                      </TouchableOpacity>
                    );
                  })}
                </View>
              </View>
            ) : null}
 
            {/* Birth Date */}
            {vm.canEditBirthDate ? (
              <View style={styles.fieldGroup}>
                <Text style={styles.fieldLabel}>Birth Date</Text>
                <View style={styles.dateInputContainer}>
                  <TextInput
                    style={[
                      styles.textInput,
                      styles.dateInputText,
                      vm.errors.birthDate ? styles.textInputError : null,
                    ]}
                    value={vm.formData.birthDate}
                    onChangeText={(text) => vm.updateField('birthDate', text)}
                    placeholder="dd.mm.yyyy"
                    placeholderTextColor="#9CA3AF"
                    accessibilityLabel="Birth date"
                  />
                  <TouchableOpacity
                    style={styles.calendarIconInside}
                    onPress={() => setShowDatePicker((prev) => !prev)}
                    activeOpacity={0.7}
                    accessibilityLabel="Pick birth date"
                  >
                    <Ionicons name="calendar-outline" size={20} color="#6B7280" />
                  </TouchableOpacity>
                </View>
                {vm.errors.birthDate ? (
                  <Text style={styles.fieldError}>{vm.errors.birthDate}</Text>
                ) : null}
              </View>
            ) : null}
 
            {showDatePicker && vm.canEditBirthDate ? (
              <View style={styles.datePickerWrapper}>
                <DateTimePicker
                  value={getPickerDate()}
                  mode="date"
                  display={Platform.OS === 'ios' ? 'inline' : 'default'}
                  maximumDate={new Date()}
                  onValueChange={handleDateChange}
                  onDismiss={() => setShowDatePicker(false)}
                />
              </View>
            ) : null}
 
            {/* Save Button */}
            <TouchableOpacity
              style={[
                styles.saveButton,
                vm.isSaving && styles.saveButtonDisabled,
              ]}
              onPress={handleSave}
              disabled={vm.isSaving}
              accessibilityRole="button"
              accessibilityLabel="Save profile"
            >
              {vm.isSaving ? (
                <ActivityIndicator size="small" color="#FFFFFF" />
              ) : (
                <>
                  <Ionicons name="checkmark-circle-outline" size={20} color="#FFFFFF" />
                  <Text style={styles.saveButtonText}>Save Changes</Text>
                </>
              )}
            </TouchableOpacity>
          </View>
        )}
      </ScrollView>
    </KeyboardAvoidingView>
  );
}
 
const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#F8FAFC',
  },
  scrollContent: {
    paddingHorizontal: 20,
    paddingBottom: 40,
    paddingTop: 60,
  },
  header: {
    flexDirection: 'row',
    alignItems: 'center',
    paddingBottom: 16,
  },
  backButton: {
    padding: 4,
  },
  screenTitle: {
    flex: 1,
    fontSize: 22,
    fontWeight: '800',
    color: '#111827',
    textAlign: 'center',
  },
  headerSpacer: {
    width: 36,
  },
  errorBanner: {
    backgroundColor: '#FEF2F2',
    borderColor: '#FECACA',
    borderWidth: 1,
    borderRadius: 12,
    padding: 12,
    marginBottom: 12,
  },
  errorBannerText: {
    color: '#DC2626',
    fontSize: 14,
  },
  successBanner: {
    backgroundColor: '#F0FDF4',
    borderColor: '#BBF7D0',
    borderWidth: 1,
    borderRadius: 12,
    padding: 12,
    marginBottom: 12,
  },
  successBannerText: {
    color: '#16A34A',
    fontSize: 14,
    fontWeight: '600',
  },
  loadingContainer: {
    paddingVertical: 64,
    alignItems: 'center',
    justifyContent: 'center',
  },
  loadingText: {
    marginTop: 12,
    color: '#6B7280',
    fontSize: 15,
  },
  formCard: {
    backgroundColor: '#FFFFFF',
    borderRadius: 24,
    padding: 24,
    shadowColor: '#000',
    shadowOpacity: 0.06,
    shadowRadius: 16,
    shadowOffset: { width: 0, height: 6 },
    elevation: 3,
    gap: 20,
  },
  fieldGroup: {
    gap: 6,
  },
  fieldLabel: {
    fontSize: 14,
    fontWeight: '700',
    color: '#374151',
  },
  textInput: {
    flex: 1,
    borderWidth: 1.5,
    borderColor: '#E5E7EB',
    borderRadius: 12,
    paddingHorizontal: 14,
    paddingVertical: 12,
    fontSize: 15,
    color: '#111827',
    backgroundColor: '#FAFAFA',
  },
  locationInputRow: {
    flexDirection: 'row',
    alignItems: 'center',
    gap: 8,
  },
  textInputError: {
    borderColor: '#DC2626',
  },
  textArea: {
    minHeight: 100,
    textAlignVertical: 'top',
  },
  charCount: {
    fontSize: 12,
    color: '#9CA3AF',
    textAlign: 'right',
  },
  fieldError: {
    fontSize: 13,
    color: '#DC2626',
  },
  genderRow: {
    flexDirection: 'row',
    flexWrap: 'wrap',
    gap: 8,
  },
  genderChip: {
    paddingHorizontal: 14,
    paddingVertical: 8,
    borderRadius: 10,
    borderWidth: 1.5,
    borderColor: '#E5E7EB',
    backgroundColor: '#FAFAFA',
  },
  genderChipSelected: {
    borderColor: '#0F172A',
    backgroundColor: '#0F172A',
  },
  genderChipText: {
    fontSize: 14,
    fontWeight: '600',
    color: '#6B7280',
  },
  genderChipTextSelected: {
    color: '#FFFFFF',
  },
  dateInputContainer: {
    position: 'relative',
    justifyContent: 'center',
  },
  dateInputText: {
    paddingRight: 46,
  },
  calendarIconInside: {
    position: 'absolute',
    right: 14,
    width: 32,
    height: 32,
    alignItems: 'center',
    justifyContent: 'center',
  },
  datePickerWrapper: {
    alignItems: 'center',
    marginBottom: 4,
    backgroundColor: '#FFFFFF',
    borderRadius: 12,
  },
  clearLocationBtn: {
    padding: 10,
    backgroundColor: '#F3F4F6',
    borderRadius: 10,
  },
  clearLocationText: {
    fontSize: 14,
    fontWeight: '600',
    color: '#6B7280',
  },
  searchSpinner: {
    marginTop: 8,
  },
  suggestionsContainer: {
    marginTop: 4,
    borderWidth: 1,
    borderColor: '#E5E7EB',
    borderRadius: 10,
    backgroundColor: '#FFFFFF',
    overflow: 'hidden',
  },
  suggestionItem: {
    paddingHorizontal: 14,
    paddingVertical: 10,
    borderBottomWidth: 1,
    borderBottomColor: '#F3F4F6',
  },
  suggestionText: {
    fontSize: 14,
    color: '#374151',
  },
  saveButton: {
    backgroundColor: '#0F172A',
    borderRadius: 14,
    paddingVertical: 14,
    flexDirection: 'row',
    alignItems: 'center',
    justifyContent: 'center',
    gap: 8,
    marginTop: 4,
  },
  saveButtonDisabled: {
    opacity: 0.7,
  },
  saveButtonText: {
    color: '#FFFFFF',
    fontSize: 16,
    fontWeight: '700',
  },
});