import 'package:flutter/material.dart'; import '../models/profile.dart'; import '../models/group.dart'; import '../models/norms.dart'; import '../services/api_service.dart'; import '../services/session_manager.dart'; import '../widgets/item_rating_card.dart'; import '../widgets/loading_spinner.dart'; class ProfileEditScreen extends StatefulWidget { final Profile? profile; const ProfileEditScreen({super.key, this.profile}); @override State createState() => _ProfileEditScreenState(); } class _ProfileEditScreenState extends State with SingleTickerProviderStateMixin { late TabController _tabController; final _nameController = TextEditingController(); Group? _selectedGroup; String _newGroupName = ''; List _groups = []; List _seItems = List.filled(36, 2); List _feItems = List.filled(36, 2); bool _isLoading = true; bool _isSaving = false; bool _showNewGroupField = false; @override void initState() { super.initState(); _tabController = TabController(length: 2, vsync: this); if (widget.profile != null) { _nameController.text = widget.profile!.name; _seItems = List.from(widget.profile!.seItems); _feItems = List.from(widget.profile!.feItems); } _loadGroups(); } Future _loadGroups() async { try { final apiService = ApiService(); final groups = await apiService.getGroups(); setState(() { _groups = groups; if (widget.profile?.gruppeID != null) { _selectedGroup = groups.firstWhere( (g) => g.gruppeID.toString() == widget.profile!.gruppeID, orElse: () => groups.first, ); } _isLoading = false; }); } catch (e) { setState(() => _isLoading = false); _showError('Gruppen konnten nicht geladen werden'); } } Future _save() async { if (_nameController.text.trim().isEmpty) { _showError('Bitte geben Sie einen Namen ein'); return; } setState(() => _isSaving = true); int? finalGroupId; if (_showNewGroupField && _newGroupName.trim().isNotEmpty) { try { final apiService = ApiService(); final success = await apiService.createGroup(_newGroupName.trim()); if (success) { final updatedGroups = await apiService.getGroups(); final newGroup = updatedGroups.firstWhere( (g) => g.name == _newGroupName.trim(), ); finalGroupId = newGroup.gruppeID; } } catch (e) { _showError('Gruppe konnte nicht erstellt werden'); setState(() => _isSaving = false); return; } } else if (_selectedGroup != null) { finalGroupId = _selectedGroup!.gruppeID; } final profile = Profile( profilID: widget.profile?.profilID ?? '', name: _nameController.text.trim(), gruppename: _selectedGroup?.name ?? (_newGroupName.trim().isNotEmpty ? _newGroupName.trim() : null), gruppeID: finalGroupId?.toString(), seItems: _seItems, feItems: _feItems, ); try { final apiService = ApiService(); bool success; if (widget.profile != null) { success = await apiService.updateProfile(profile); } else { success = await apiService.createProfile(profile); } if (success && mounted) { Navigator.pop(context, true); } else { _showError('Speichern fehlgeschlagen'); } } catch (e) { _showError('Fehler: $e'); } finally { if (mounted) setState(() => _isSaving = false); } } void _showError(String message) { ScaffoldMessenger.of(context).showSnackBar( SnackBar(content: Text(message), backgroundColor: Colors.red), ); } @override Widget build(BuildContext context) { if (_isLoading) { return const Scaffold(body: LoadingSpinner()); } return Scaffold( appBar: AppBar( title: Text(widget.profile == null ? 'Neues Profil' : 'Profil bearbeiten'), bottom: TabBar( controller: _tabController, tabs: const [ Tab(text: 'Selbsteinschätzung'), Tab(text: 'Fremdeinschätzung'), ], ), ), body: Column( children: [ Padding( padding: const EdgeInsets.all(16), child: Column( children: [ TextField( controller: _nameController, decoration: const InputDecoration( labelText: 'Name *', border: OutlineInputBorder(), ), ), const SizedBox(height: 12), if (!_showNewGroupField) DropdownButtonFormField( value: _selectedGroup, decoration: const InputDecoration( labelText: 'Gruppe', border: OutlineInputBorder(), ), items: [ const DropdownMenuItem(value: null, child: Text('Keine Gruppe')), ..._groups.map((g) => DropdownMenuItem(value: g, child: Text(g.name))), const DropdownMenuItem(value: null, child: Text('+ Neue Gruppe...')), ], onChanged: (value) { if (value == null && _selectedGroup != null) { setState(() { _showNewGroupField = true; _selectedGroup = null; }); } else { setState(() => _selectedGroup = value); } }, ), if (_showNewGroupField) Column( children: [ TextField( decoration: const InputDecoration( labelText: 'Neue Gruppe', border: OutlineInputBorder(), ), onChanged: (value) => _newGroupName = value, ), TextButton( onPressed: () => setState(() => _showNewGroupField = false), child: const Text('Abbrechen'), ), ], ), ], ), ), Expanded( child: TabBarView( controller: _tabController, children: [ _buildItemsList(_seItems, true), _buildItemsList(_feItems, false), ], ), ), ], ), bottomNavigationBar: BottomAppBar( child: Padding( padding: const EdgeInsets.all(16), child: Row( children: [ Expanded( child: OutlinedButton( onPressed: () => Navigator.pop(context), child: const Text('Abbrechen'), ), ), const SizedBox(width: 16), Expanded( child: ElevatedButton( onPressed: _isSaving ? null : _save, child: _isSaving ? const SizedBox( height: 20, width: 20, child: CircularProgressIndicator(strokeWidth: 2), ) : const Text('Speichern'), ), ), ], ), ), ), ); } Widget _buildItemsList(List items, bool isSE) { return ListView.builder( padding: const EdgeInsets.all(16), itemCount: 36, itemBuilder: (context, index) { return ItemRatingCard( index: index, itemName: Norms.items[index], value: items[index], onChanged: (newValue) { setState(() { if (isSE) { _seItems[index] = newValue; } else { _feItems[index] = newValue; } }); }, ); }, ); } }