import React, { useState } from 'react';
import { Alert, View, Text, TextInput, Button } from 'react-native';
import { MFADeviceType } from '@dynamic-labs/sdk-api-core';
import * as Clipboard from 'expo-clipboard';
import { useDynamic } from './path-to-your-client';
export function AccountTotpMfa() {
const client = useDynamic();
const [step, setStep] = useState<'setup' | 'verify'>('setup');
const [deviceInfo, setDeviceInfo] = useState<{
id: string;
secret: string;
} | null>(null);
const [verificationCode, setVerificationCode] = useState('');
const [loading, setLoading] = useState(false);
const handleAddDevice = async () => {
try {
setLoading(true);
const result = await client.mfa.addDevice(MFADeviceType.Totp);
setDeviceInfo(result);
setStep('verify');
} catch (error) {
console.error('Failed to add MFA device:', error);
Alert.alert('Error', 'Failed to add MFA device');
} finally {
setLoading(false);
}
};
const handleVerifyDevice = async () => {
if (!deviceInfo || !verificationCode.trim()) {
Alert.alert('Error', 'Please enter the verification code');
return;
}
try {
setLoading(true);
await client.mfa.verifyDevice(verificationCode, MFADeviceType.Totp);
Alert.alert('Success', 'MFA device added successfully');
} catch (error) {
console.error('Failed to verify MFA device:', error);
Alert.alert(
'Error',
'Failed to verify MFA device. Please check your code and try again.',
);
} finally {
setLoading(false);
}
};
if (step === 'setup') {
return (
<View>
<Text>Set up Authenticator App</Text>
<Button
title="Generate Secret"
onPress={handleAddDevice}
disabled={loading}
/>
</View>
);
}
return (
<View>
<Text>Copy Secret: {deviceInfo?.secret}</Text>
<Button
title="Copy Secret"
onPress={() => Clipboard.setStringAsync(deviceInfo!.secret)}
/>
<TextInput
placeholder="Enter 6-digit code"
value={verificationCode}
onChangeText={setVerificationCode}
keyboardType="numeric"
maxLength={6}
/>
<Button
title="Verify & Add Device"
onPress={handleVerifyDevice}
disabled={loading}
/>
</View>
);
}