import 'package:flutter/material.dart'; import 'package:get/get.dart'; import 'package:flutter_screenutil/flutter_screenutil.dart'; import '../../core/services/chit_group_service.dart'; import '../../core/services/api_service.dart'; import '../../core/models/chit_group.dart'; import '../../core/models/group_member.dart'; import '../../core/utils/snackbar_util.dart'; class AddPastDrawDialog extends StatefulWidget { final ChitGroup group; final int monthNumber; const AddPastDrawDialog({ super.key, required this.group, required this.monthNumber, }); @override State createState() => _AddPastDrawDialogState(); } class _AddPastDrawDialogState extends State { final _formKey = GlobalKey(); final _prizeAmountController = TextEditingController(); final _apiService = ApiService(); String? _selectedMemberId; String? _selectedMemberName; bool _isLoading = false; int _selectedMonth = 1; int _selectedYear = DateTime.now().year; @override void initState() { super.initState(); _selectedMonth = widget.monthNumber; _calculateMonthYear(); _prizeAmountController.text = widget.group.monthlyInstallment.toStringAsFixed(0); } void _calculateMonthYear() { if (widget.group.startDate != null) { final startDate = widget.group.startDate!; final targetDate = DateTime( startDate.year, startDate.month + widget.monthNumber - 1, startDate.day, ); _selectedMonth = targetDate.month; _selectedYear = targetDate.year; } } @override void dispose() { _prizeAmountController.dispose(); super.dispose(); } Future _handleSubmit() async { if (_formKey.currentState!.validate()) { if (_selectedMemberId == null) { SnackbarUtil.showError('Please select a winner'); return; } setState(() => _isLoading = true); try { final response = await _apiService.createMonthlyDraw({ 'group_id': widget.group.id, 'month': _selectedMonth, 'year': _selectedYear, 'winner_id': _selectedMemberId, 'prize_amount': double.parse(_prizeAmountController.text), 'client_seed': 'PAST_DRAW_${DateTime.now().millisecondsSinceEpoch}', 'is_past_draw': true, // Flag for past draw }); if (response['success']) { SnackbarUtil.showSuccess( 'Past draw result added successfully', title: 'Success', ); Get.back(result: true); } else { SnackbarUtil.showError( response['message'] ?? 'Failed to add draw', title: 'Error', ); } } catch (e) { SnackbarUtil.showError('Error: ${e.toString()}'); } finally { setState(() => _isLoading = false); } } } @override Widget build(BuildContext context) { return Dialog( shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(20.r)), child: Container( width: 500.w, padding: EdgeInsets.all(24.w), child: Form( key: _formKey, child: Column( mainAxisSize: MainAxisSize.min, crossAxisAlignment: CrossAxisAlignment.start, children: [ // Header Row( children: [ Icon(Icons.history, color: Colors.blue.shade600, size: 28.w), SizedBox(width: 12.w), Expanded( child: Text( 'Add Past Draw Result', style: TextStyle( fontSize: 20.sp, fontWeight: FontWeight.bold, ), ), ), IconButton( icon: const Icon(Icons.close), onPressed: () => Get.back(), ), ], ), SizedBox(height: 24.h), // Month Info Container( padding: EdgeInsets.all(16.w), decoration: BoxDecoration( color: Colors.blue.shade50, borderRadius: BorderRadius.circular(12.r), border: Border.all(color: Colors.blue.shade200), ), child: Row( mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [ Text( 'Month ${widget.monthNumber}', style: TextStyle( fontSize: 18.sp, fontWeight: FontWeight.bold, color: Colors.blue.shade800, ), ), Text( '$_selectedMonth/$_selectedYear', style: TextStyle( fontSize: 16.sp, fontWeight: FontWeight.w600, color: Colors.blue.shade700, ), ), ], ), ), SizedBox(height: 20.h), // Select Winner Text( 'Who Won This Draw?', style: TextStyle( fontSize: 16.sp, fontWeight: FontWeight.w600, ), ), SizedBox(height: 12.h), Obx(() { final members = Get.find().groupMembers; if (members.isEmpty) { return Container( padding: EdgeInsets.all(16.w), decoration: BoxDecoration( color: Colors.orange.shade50, borderRadius: BorderRadius.circular(12.r), border: Border.all(color: Colors.orange.shade200), ), child: Text( 'Please add members to the group first', style: TextStyle( color: Colors.orange.shade900, fontSize: 14.sp, ), ), ); } return Container( decoration: BoxDecoration( border: Border.all(color: Colors.grey.shade300), borderRadius: BorderRadius.circular(12.r), ), child: Column( children: members.map((member) { final isSelected = member.id == _selectedMemberId; return InkWell( onTap: () { setState(() { _selectedMemberId = member.userId; _selectedMemberName = member.user?.fullName ?? 'Unknown'; }); }, child: Container( padding: EdgeInsets.all(12.w), decoration: BoxDecoration( color: isSelected ? Colors.green.shade50 : null, border: Border( bottom: BorderSide(color: Colors.grey.shade200), ), ), child: Row( children: [ Icon( isSelected ? Icons.radio_button_checked : Icons.radio_button_unchecked, color: isSelected ? Colors.green.shade600 : Colors.grey.shade400, ), SizedBox(width: 12.w), Expanded( child: Text( member.user?.fullName ?? 'Unknown', style: TextStyle( fontSize: 16.sp, fontWeight: isSelected ? FontWeight.w600 : FontWeight.normal, ), ), ), if (isSelected) Icon(Icons.check_circle, color: Colors.green.shade600), ], ), ), ); }).toList(), ), ); }), SizedBox(height: 20.h), // Prize Amount Text( 'Prize Amount', style: TextStyle( fontSize: 16.sp, fontWeight: FontWeight.w600, ), ), SizedBox(height: 8.h), TextFormField( controller: _prizeAmountController, keyboardType: TextInputType.number, decoration: InputDecoration( hintText: 'Prize amount won', prefixText: '₹ ', border: OutlineInputBorder(borderRadius: BorderRadius.circular(12.r)), filled: true, fillColor: Colors.grey.shade50, ), validator: (value) { if (value?.isEmpty ?? true) return 'Required'; if (double.tryParse(value!) == null) return 'Invalid amount'; return null; }, ), SizedBox(height: 24.h), // Actions Row( children: [ Expanded( child: OutlinedButton( onPressed: _isLoading ? null : () => Get.back(), style: OutlinedButton.styleFrom( padding: EdgeInsets.symmetric(vertical: 14.h), shape: RoundedRectangleBorder( borderRadius: BorderRadius.circular(12.r), ), ), child: Text( 'Cancel', style: TextStyle(fontSize: 16.sp), ), ), ), SizedBox(width: 16.w), Expanded( child: ElevatedButton( onPressed: _isLoading ? null : _handleSubmit, style: ElevatedButton.styleFrom( backgroundColor: Colors.blue.shade600, foregroundColor: Colors.white, padding: EdgeInsets.symmetric(vertical: 14.h), shape: RoundedRectangleBorder( borderRadius: BorderRadius.circular(12.r), ), ), child: _isLoading ? SizedBox( height: 20.h, width: 20.w, child: const CircularProgressIndicator( strokeWidth: 2, valueColor: AlwaysStoppedAnimation(Colors.white), ), ) : Text( 'Add Draw', style: TextStyle(fontSize: 16.sp, fontWeight: FontWeight.w600), ), ), ), ], ), ], ), ), ), ); } }