import 'package:flutter/material.dart'; import 'package:flutter_riverpod/flutter_riverpod.dart'; import 'package:go_router/go_router.dart'; import 'package:worldhopper/l10n/app_localizations.dart'; import 'package:worldhopper/helpers/snackbar_helper.dart'; import 'package:worldhopper/models/server.dart'; import 'package:worldhopper/providers/server_provider.dart'; import 'package:worldhopper/providers/server_software_provider.dart'; import 'package:worldhopper/services/server_software/server_software_type.dart'; /// Screen for editing an existing 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(); final _urlFocusNode = FocusNode(); bool _requiresAuth = false; bool _obscurePassword = true; bool _isLoading = false; bool _isTesting = false; Server? _originalServer; ServerSoftwareType _selectedServerType = ServerSoftwareType.generic; bool _serverTypeManuallySet = false; @override void initState() { super.initState(); _urlFocusNode.addListener(_onUrlFocusChange); } @override void dispose() { _nameController.dispose(); _urlController.dispose(); _usernameController.dispose(); _passwordController.dispose(); _urlFocusNode.removeListener(_onUrlFocusChange); _urlFocusNode.dispose(); super.dispose(); } void _onUrlFocusChange() { if (!_urlFocusNode.hasFocus && !_serverTypeManuallySet) { _autoDetectServerType(); } } void _autoDetectServerType() { final url = _urlController.text.trim(); if (url.isEmpty) return; final uri = Uri.tryParse(url); if (uri == null || !uri.hasScheme || !uri.hasAuthority) return; final tempServer = Server( id: '', name: '', url: url, createdAt: DateTime.now(), ); final softwareService = ref.read(serverSoftwareServiceProvider); final detected = softwareService.detect(tempServer); if (detected != _selectedServerType) { setState(() { _selectedServerType = detected; }); } } String _serverTypeLabel(ServerSoftwareType type, AppLocalizations l10n) { return switch (type) { ServerSoftwareType.generic => l10n.serverTypeGeneric, ServerSoftwareType.kavita => l10n.serverTypeKavita, }; } @override Widget build(BuildContext context) { final l10n = AppLocalizations.of(context); final serverAsync = ref.watch(serverProvider(widget.serverId)); return Scaffold( appBar: AppBar( title: Text(l10n.editServerTitle), ), body: serverAsync.when( data: (server) { if (server == null) { return Center( child: Text(l10n.editServerNotFound), ); } // 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!; } _selectedServerType = server.softwareType ?? ServerSoftwareType.generic; } return Form( key: _formKey, child: ListView( padding: const EdgeInsets.all(16), children: [ // Name field TextFormField( controller: _nameController, decoration: InputDecoration( labelText: l10n.addServerNameLabel, prefixIcon: const Icon(Icons.label), ), textInputAction: TextInputAction.next, validator: (value) { if (value == null || value.trim().isEmpty) { return l10n.addServerValidationNameRequired; } return null; }, ), const SizedBox(height: 16), // URL field TextFormField( controller: _urlController, focusNode: _urlFocusNode, decoration: InputDecoration( labelText: l10n.addServerUrlLabel, prefixIcon: const Icon(Icons.link), ), keyboardType: TextInputType.url, textInputAction: TextInputAction.next, validator: (value) { if (value == null || value.trim().isEmpty) { return l10n.addServerValidationUrlRequired; } final uri = Uri.tryParse(value.trim()); if (uri == null || !uri.hasScheme || !uri.hasAuthority) { return l10n.addServerValidationUrlInvalid; } if (uri.scheme != 'http' && uri.scheme != 'https') { return l10n.addServerValidationUrlScheme; } return null; }, ), const SizedBox(height: 16), // Server Type dropdown DropdownButtonFormField( initialValue: _selectedServerType, decoration: InputDecoration( labelText: l10n.addServerServerType, helperText: l10n.addServerServerTypeSubtitle, prefixIcon: const Icon(Icons.dns), ), items: ServerSoftwareType.values.map((type) { return DropdownMenuItem( value: type, child: Text(_serverTypeLabel(type, l10n)), ); }).toList(), onChanged: (value) { if (value != null) { setState(() { _selectedServerType = value; _serverTypeManuallySet = true; }); } }, ), const SizedBox(height: 24), // Authentication toggle SwitchListTile( title: Text(l10n.addServerAuth), subtitle: Text(l10n.addServerAuthSubtitle), value: _requiresAuth, onChanged: (value) { setState(() { _requiresAuth = value; if (!value) { _usernameController.clear(); _passwordController.clear(); } }); }, ), const SizedBox(height: 16), // Authentication fields if (_requiresAuth) ...[ TextFormField( controller: _usernameController, decoration: InputDecoration( labelText: l10n.addServerUsername, prefixIcon: const Icon(Icons.person), ), textInputAction: TextInputAction.next, validator: (value) { if (_requiresAuth && (value == null || value.trim().isEmpty)) { return l10n.addServerValidationUsernameRequired; } return null; }, ), const SizedBox(height: 16), TextFormField( controller: _passwordController, decoration: InputDecoration( labelText: l10n.addServerPassword, 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 l10n.addServerValidationPasswordRequired; } return null; }, onFieldSubmitted: (_) => _saveServer(), ), const SizedBox(height: 24), ], // Test connection button OutlinedButton.icon( onPressed: _isLoading || _isTesting ? null : _testConnection, icon: _isTesting ? const SizedBox( height: 16, width: 16, child: CircularProgressIndicator(strokeWidth: 2), ) : const Icon(Icons.wifi_find), label: Text( _isTesting ? l10n.testConnectionTesting : l10n.testConnectionButton, ), ), const SizedBox(height: 16), // Server metadata Card( color: Theme.of(context).colorScheme.surfaceContainerHighest, child: Padding( padding: const EdgeInsets.all(16), child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ Text( l10n.editServerInfo, style: Theme.of(context).textTheme.titleSmall?.copyWith( fontWeight: FontWeight.bold, ), ), const SizedBox(height: 8), _buildInfoRow( l10n.editServerAdded, _formatDateTime(server.createdAt), ), if (server.lastSyncedAt != null) _buildInfoRow( l10n.editServerLastSynced, _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), ) : Text(l10n.editServerSaveButton), ), ], ), ); }, 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(l10n.editServerErrorLoading(error.toString())), ], ), ), ), ); } 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 .withValues(alpha: 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 _testConnection() async { final url = _urlController.text.trim(); if (url.isEmpty) return; setState(() => _isTesting = true); try { final l10n = AppLocalizations.of(context); final tempServer = Server( id: 'test', name: 'Test', url: url, username: _requiresAuth ? _usernameController.text.trim() : null, password: _requiresAuth ? _passwordController.text : null, createdAt: DateTime.now(), softwareType: _selectedServerType, ); final softwareService = ref.read(serverSoftwareServiceProvider); final software = softwareService.getImplementation(tempServer); await software.testConnection(tempServer); if (!mounted) return; context.showSuccessSnackBar(l10n.testConnectionSuccess); } catch (e) { if (mounted) { final l10n = AppLocalizations.of(context); debugPrint('testConnection failed: $e'); context.showErrorSnackBar(l10n.testConnectionError(e.toString())); } } finally { if (mounted) setState(() => _isTesting = false); } } Future _saveServer() async { if (!_formKey.currentState!.validate()) { return; } setState(() { _isLoading = true; }); try { final l10n = AppLocalizations.of(context); // 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, softwareType: _selectedServerType, ); // Clear cached state if credentials changed final softwareService = ref.read(serverSoftwareServiceProvider); if (_originalServer!.username != updatedServer.username || _originalServer!.password != updatedServer.password) { softwareService.clearCachedState(updatedServer.id); } // Save server await ref .read(serverNotifierProvider.notifier) .updateServer(updatedServer); if (mounted) { context.showSuccessSnackBar(l10n.editServerSuccess(updatedServer.name)); context.pop(); } } catch (e) { if (mounted) { final l10n = AppLocalizations.of(context); context.showErrorSnackBar(l10n.editServerError(e.toString())); } } finally { if (mounted) { setState(() { _isLoading = false; }); } } } }