import 'package:flutter/material.dart'; import 'package:flutter_riverpod/flutter_riverpod.dart'; import 'package:go_router/go_router.dart'; import 'package:worldhopper/models/opds_server.dart'; import 'package:worldhopper/providers/server_provider.dart'; /// Screen for editing an existing OPDS server class EditServerScreen extends ConsumerStatefulWidget { final String serverId; const EditServerScreen({ super.key, required this.serverId, }); @override ConsumerState createState() => _EditServerScreenState(); } class _EditServerScreenState extends ConsumerState { final _formKey = GlobalKey(); final _nameController = TextEditingController(); final _urlController = TextEditingController(); final _usernameController = TextEditingController(); final _passwordController = TextEditingController(); bool _requiresAuth = false; bool _obscurePassword = true; bool _isLoading = false; OPDSServer? _originalServer; @override void dispose() { _nameController.dispose(); _urlController.dispose(); _usernameController.dispose(); _passwordController.dispose(); super.dispose(); } @override Widget build(BuildContext context) { final serverAsync = ref.watch(serverProvider(widget.serverId)); return Scaffold( appBar: AppBar( title: const Text('Edit Server'), ), body: serverAsync.when( data: (server) { if (server == null) { return const Center( child: Text('Server not found'), ); } // Initialize form fields if not already done if (_originalServer == null) { _originalServer = server; _nameController.text = server.name; _urlController.text = server.url; _requiresAuth = server.requiresAuth; if (server.username != null) { _usernameController.text = server.username!; } if (server.password != null) { _passwordController.text = server.password!; } } return Form( key: _formKey, child: ListView( padding: const EdgeInsets.all(16), children: [ // Name field TextFormField( controller: _nameController, decoration: const InputDecoration( labelText: 'Server Name', prefixIcon: Icon(Icons.label), ), textInputAction: TextInputAction.next, validator: (value) { if (value == null || value.trim().isEmpty) { return 'Please enter a server name'; } return null; }, ), const SizedBox(height: 16), // URL field TextFormField( controller: _urlController, decoration: const InputDecoration( labelText: 'Server URL', prefixIcon: Icon(Icons.link), ), keyboardType: TextInputType.url, textInputAction: TextInputAction.next, validator: (value) { if (value == null || value.trim().isEmpty) { return 'Please enter a server URL'; } final uri = Uri.tryParse(value.trim()); if (uri == null || !uri.hasScheme || !uri.hasAuthority) { return 'Please enter a valid URL'; } if (uri.scheme != 'http' && uri.scheme != 'https') { return 'URL must start with http:// or https://'; } return null; }, ), const SizedBox(height: 24), // Authentication toggle SwitchListTile( title: const Text('Requires Authentication'), subtitle: const Text('Enable if server requires login'), value: _requiresAuth, onChanged: (value) { setState(() { _requiresAuth = value; if (!value) { _usernameController.clear(); _passwordController.clear(); } }); }, ), const SizedBox(height: 16), // Authentication fields (conditionally shown) if (_requiresAuth) ...[ TextFormField( controller: _usernameController, decoration: const InputDecoration( labelText: 'Username', prefixIcon: Icon(Icons.person), ), textInputAction: TextInputAction.next, validator: (value) { if (_requiresAuth && (value == null || value.trim().isEmpty)) { return 'Please enter a username'; } return null; }, ), const SizedBox(height: 16), TextFormField( controller: _passwordController, decoration: InputDecoration( labelText: 'Password', prefixIcon: const Icon(Icons.lock), suffixIcon: IconButton( icon: Icon( _obscurePassword ? Icons.visibility : Icons.visibility_off, ), onPressed: () { setState(() { _obscurePassword = !_obscurePassword; }); }, ), ), obscureText: _obscurePassword, textInputAction: TextInputAction.done, validator: (value) { if (_requiresAuth && (value == null || value.isEmpty)) { return 'Please enter a password'; } return null; }, onFieldSubmitted: (_) => _saveServer(), ), const SizedBox(height: 24), ], // Server metadata Card( color: Theme.of(context).colorScheme.surfaceContainerHighest, child: Padding( padding: const EdgeInsets.all(16), child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ Text( 'Server Information', style: Theme.of(context) .textTheme .titleSmall ?.copyWith( fontWeight: FontWeight.bold, ), ), const SizedBox(height: 8), _buildInfoRow( 'Added', _formatDateTime(server.createdAt), ), if (server.lastSyncedAt != null) _buildInfoRow( 'Last Synced', _formatDateTime(server.lastSyncedAt!), ), ], ), ), ), const SizedBox(height: 32), // Save button FilledButton( onPressed: _isLoading ? null : _saveServer, child: _isLoading ? const SizedBox( height: 20, width: 20, child: CircularProgressIndicator(strokeWidth: 2), ) : const Text('Save Changes'), ), ], ), ); }, loading: () => const Center(child: CircularProgressIndicator()), error: (error, stack) => Center( child: Column( mainAxisAlignment: MainAxisAlignment.center, children: [ const Icon(Icons.error_outline, size: 48, color: Colors.red), const SizedBox(height: 16), Text('Error loading server: $error'), ], ), ), ), ); } Widget _buildInfoRow(String label, String value) { return Padding( padding: const EdgeInsets.only(top: 4), child: Row( mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [ Text( label, style: Theme.of(context).textTheme.bodySmall?.copyWith( color: Theme.of(context) .colorScheme .onSurface .withOpacity(0.6), ), ), Text( value, style: Theme.of(context).textTheme.bodySmall, ), ], ), ); } String _formatDateTime(DateTime dateTime) { return '${dateTime.year}-${dateTime.month.toString().padLeft(2, '0')}-${dateTime.day.toString().padLeft(2, '0')} ' '${dateTime.hour.toString().padLeft(2, '0')}:${dateTime.minute.toString().padLeft(2, '0')}'; } Future _saveServer() async { if (!_formKey.currentState!.validate()) { return; } setState(() { _isLoading = true; }); try { // Create updated server final updatedServer = _originalServer!.copyWith( name: _nameController.text.trim(), url: _urlController.text.trim(), username: _requiresAuth ? _usernameController.text.trim() : null, password: _requiresAuth ? _passwordController.text : null, ); // Save server await ref .read(serverNotifierProvider.notifier) .updateServer(updatedServer); if (mounted) { // Show success message ScaffoldMessenger.of(context).showSnackBar( SnackBar( content: Text('${updatedServer.name} updated successfully'), backgroundColor: Colors.green, ), ); // Navigate back context.pop(); } } catch (e) { if (mounted) { ScaffoldMessenger.of(context).showSnackBar( SnackBar( content: Text('Error updating server: $e'), backgroundColor: Colors.red, ), ); } } finally { if (mounted) { setState(() { _isLoading = false; }); } } } }