import 'package:flutter/material.dart'; import '../../../../domain/services/cryptography/asymmetric_crypto_service.dart'; import 'package:provider/provider.dart'; /// Cryptographic key management page class ManageKeysPage extends StatefulWidget { @override _ManageKeysPageState createState() => _ManageKeysPageState(); } class _ManageKeysPageState extends State { String? publicKey; bool _isLoading = false; bool _hasError = false; String _errorMessage = ''; @override void initState() { super.initState(); _loadPublicKey(); } Future _loadPublicKey() async { setState(() { _isLoading = true; _hasError = false; }); try { final cryptoService = context.read(); final key = await cryptoService.getPublicKeyPem(); if (mounted) { setState(() { publicKey = key; _isLoading = false; }); } } catch (e) { if (mounted) { setState(() { _hasError = true; _errorMessage = 'Failed to load public key: $e'; _isLoading = false; }); } } } Future _regenerateKeyPair() async { setState(() { _isLoading = true; _hasError = false; }); try { final cryptoService = context.read(); await cryptoService.generateAndStoreKeyPair(); await _loadPublicKey(); if (mounted) { ScaffoldMessenger.of(context).showSnackBar( const SnackBar(content: Text('New key pair generated!')), ); } } catch (e) { if (mounted) { setState(() { _hasError = true; _errorMessage = 'Failed to generate key pair: $e'; _isLoading = false; }); ScaffoldMessenger.of(context).showSnackBar( SnackBar(content: Text('Error generating key pair: $e')), ); } } } @override Widget build(BuildContext context) { return Scaffold( backgroundColor: Colors.black, appBar: AppBar( title: const Text('Key Management'), ), body: Padding( padding: const EdgeInsets.all(16.0), child: _isLoading ? const Center(child: CircularProgressIndicator()) : Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ const Text( 'Your Public Key', style: TextStyle( color: Colors.white, fontSize: 18, fontWeight: FontWeight.bold, ), ), const SizedBox(height: 8), Container( width: double.infinity, padding: const EdgeInsets.all(12), decoration: BoxDecoration( color: Colors.grey[900], borderRadius: BorderRadius.circular(8), ), child: _hasError ? Text( _errorMessage, style: const TextStyle( color: Colors.red, fontFamily: 'monospace', fontSize: 12, ), ) : Text( publicKey ?? 'No key available', style: const TextStyle( color: Colors.white70, fontFamily: 'monospace', fontSize: 12, ), ), ), const SizedBox(height: 24), ElevatedButton( onPressed: _regenerateKeyPair, child: const Text('Generate New Key Pair'), ), if (_hasError) ...[ const SizedBox(height: 16), const Text( 'Note: Encryption features may be limited due to error.', style: TextStyle(color: Colors.yellow), ), ], ], ), ), ); } }