import React, { useState } from 'react'; import { StyleSheet, View } from 'react-native'; import { NativeStackScreenProps } from '@react-navigation/native-stack'; import { ScreenShell, Input, Button, Card, AppModal } from '../../../components'; import { useAddBeneficiaryMutation } from '../services/paymentsApi'; import type { PaymentsStackParamList } from '../../../navigation/types'; import { useDispatch } from 'react-redux'; import { beneficiariesActions } from '../store/beneficiariesSlice'; type Props = NativeStackScreenProps; export default function AddBeneficiaryScreen({ navigation }: Props) { const dispatch = useDispatch(); const [addBen, { isLoading }] = useAddBeneficiaryMutation(); const [form, setForm] = useState({ name: '', accountNumber: '', confirmAccountNumber: '', ifsc: '', nickname: '', }); const [otpModalVisible, setOtpModalVisible] = useState(false); const [otp, setOtp] = useState(''); const [otpError, setOtpError] = useState(undefined); const isValid = form.name.trim().length > 2 && form.accountNumber.length > 6 && form.accountNumber === form.confirmAccountNumber && form.ifsc.length === 11; const handleSubmit = () => { if (!isValid) return; setOtp(''); setOtpError(undefined); setOtpModalVisible(true); }; const closeOtpModal = () => { setOtpModalVisible(false); setOtp(''); setOtpError(undefined); }; const confirmOTPAndSave = async () => { if (otp !== '123456') { setOtpError('That code is incorrect. Use 123456 for this demo.'); return; } setOtpModalVisible(false); try { const nickname = form.nickname.trim() || undefined; const newBeneficiaryObj = { name: form.name.trim(), bankName: form.ifsc.toUpperCase().startsWith('HDFC') ? 'HDFC Bank' : 'State Bank of India', // mock logic accountMasked: form.accountNumber.slice(-4).padStart(8, 'X'), nickname, }; const payload = await addBen(newBeneficiaryObj).unwrap(); // Save into the beneficiaries slice — the single source of truth that // every payments screen reads, so the new payee shows up immediately. dispatch(beneficiariesActions.addBeneficiary({ ...payload, nickname })); navigation.goBack(); } catch (e) { console.warn("Failed to add beneficiary", e); setOtpError('We could not save this payee. Please try again.'); setOtpModalVisible(true); } }; return ( setForm({ ...form, name: v })} /> setForm({ ...form, accountNumber: v })} /> setForm({ ...form, confirmAccountNumber: v })} error={form.confirmAccountNumber.length > 0 && form.accountNumber !== form.confirmAccountNumber ? "Account numbers must match" : undefined} /> setForm({ ...form, ifsc: v })} error={form.ifsc.length > 0 && form.ifsc.length !== 11 ? 'IFSC code must be 11 characters' : undefined} /> setForm({ ...form, nickname: v })} />