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/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<AddPastDrawDialog> createState() => _AddPastDrawDialogState();
}

class _AddPastDrawDialogState extends State<AddPastDrawDialog> {
  final _formKey = GlobalKey<FormState>();
  final _prizeAmountController = TextEditingController();
  final _apiService = ApiService();
  
  String? _selectedMemberId;
  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<void> _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 {
          // Check if it's a duplicate winner error
          final isAlreadyWon = response['alreadyWon'] ?? false;
          final winnerName = response['winnerName'] ?? '';
          
          if (isAlreadyWon && winnerName.isNotEmpty) {
            SnackbarUtil.showError(
              '$winnerName has already won in a previous draw.\nEach member can only win once.',
              title: 'Duplicate Winner',
              duration: const Duration(seconds: 4),
            );
          } 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,
        constraints: BoxConstraints(
          maxHeight: MediaQuery.of(context).size.height * 0.85,
        ),
        child: Column(
          mainAxisSize: MainAxisSize.min,
          children: [
            // Fixed Header
            Container(
              padding: EdgeInsets.all(24.w),
              decoration: BoxDecoration(
                color: Colors.white,
                borderRadius: BorderRadius.only(
                  topLeft: Radius.circular(20.r),
                  topRight: Radius.circular(20.r),
                ),
                border: Border(
                  bottom: BorderSide(color: Colors.grey.shade200),
                ),
              ),
              child: 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(),
                  ),
                ],
              ),
            ),

            // Scrollable Content
            Flexible(
              child: SingleChildScrollView(
                padding: EdgeInsets.all(24.w),
                child: Form(
                  key: _formKey,
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      // 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<ChitGroupService>().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: Row(
                              children: [
                                Icon(Icons.warning_amber_rounded, 
                                  color: Colors.orange.shade700, size: 20.w),
                                SizedBox(width: 8.w),
                                Expanded(
                                  child: Text(
                                    'Please add members to the group first',
                                    style: TextStyle(
                                      color: Colors.orange.shade900,
                                      fontSize: 14.sp,
                                    ),
                                  ),
                                ),
                              ],
                            ),
                          );
                        }

                        // Get list of members who have already won
                        final monthlyDraws = Get.find<ChitGroupService>().monthlyDraws;
                        final winnerIds = monthlyDraws.map((draw) => draw.winnerId).where((id) => id != null).toSet();
                        
                        return Container(
                          constraints: BoxConstraints(
                            maxHeight: 300.h, // Limit height for scrolling
                          ),
                          decoration: BoxDecoration(
                            border: Border.all(color: Colors.grey.shade300),
                            borderRadius: BorderRadius.circular(12.r),
                          ),
                          child: ListView.builder(
                            shrinkWrap: true,
                            itemCount: members.length,
                            itemBuilder: (context, index) {
                              final member = members[index];
                              final isSelected = member.userId == _selectedMemberId;
                              final hasAlreadyWon = winnerIds.contains(member.userId);
                              final isLast = index == members.length - 1;
                              
                              return InkWell(
                                onTap: hasAlreadyWon ? null : () {
                                  setState(() {
                                    _selectedMemberId = member.userId;
                                  });
                                },
                                borderRadius: BorderRadius.vertical(
                                  top: index == 0 ? Radius.circular(12.r) : Radius.zero,
                                  bottom: isLast ? Radius.circular(12.r) : Radius.zero,
                                ),
                                child: Container(
                                  padding: EdgeInsets.symmetric(
                                    horizontal: 12.w,
                                    vertical: 14.h,
                                  ),
                                  decoration: BoxDecoration(
                                    color: hasAlreadyWon 
                                      ? Colors.grey.shade100 
                                      : (isSelected ? Colors.green.shade50 : null),
                                    border: !isLast ? Border(
                                      bottom: BorderSide(color: Colors.grey.shade200),
                                    ) : null,
                                  ),
                                  child: Row(
                                    children: [
                                      Icon(
                                        hasAlreadyWon 
                                          ? Icons.block
                                          : (isSelected ? Icons.radio_button_checked : Icons.radio_button_unchecked),
                                        color: hasAlreadyWon 
                                          ? Colors.grey.shade400 
                                          : (isSelected ? Colors.green.shade600 : Colors.grey.shade400),
                                        size: 24.w,
                                      ),
                                      SizedBox(width: 12.w),
                                      Expanded(
                                        child: Column(
                                          crossAxisAlignment: CrossAxisAlignment.start,
                                          children: [
                                            Row(
                                              children: [
                                                Expanded(
                                                  child: Text(
                                                    member.user?.fullName ?? 'Unknown',
                                                    style: TextStyle(
                                                      fontSize: 16.sp,
                                                      fontWeight: isSelected ? FontWeight.w600 : FontWeight.normal,
                                                      color: hasAlreadyWon ? Colors.grey.shade500 : null,
                                                      decoration: hasAlreadyWon ? TextDecoration.lineThrough : null,
                                                    ),
                                                  ),
                                                ),
                                                if (hasAlreadyWon) ...[
                                                  Container(
                                                    padding: EdgeInsets.symmetric(
                                                      horizontal: 6.w,
                                                      vertical: 2.h,
                                                    ),
                                                    decoration: BoxDecoration(
                                                      color: Colors.orange.shade100,
                                                      borderRadius: BorderRadius.circular(4.r),
                                                    ),
                                                    child: Text(
                                                      'Already Won',
                                                      style: TextStyle(
                                                        fontSize: 10.sp,
                                                        color: Colors.orange.shade800,
                                                        fontWeight: FontWeight.w600,
                                                      ),
                                                    ),
                                                  ),
                                                ],
                                              ],
                                            ),
                                            if (member.user?.mobileNumber != null) ...[
                                              SizedBox(height: 2.h),
                                              Text(
                                                member.user!.mobileNumber,
                                                style: TextStyle(
                                                  fontSize: 13.sp,
                                                  color: hasAlreadyWon ? Colors.grey.shade400 : Colors.grey.shade600,
                                                ),
                                              ),
                                            ],
                                          ],
                                        ),
                                      ),
                                      if (isSelected)
                                        Icon(Icons.check_circle, 
                                          color: Colors.green.shade600, size: 20.w),
                                    ],
                                  ),
                                ),
                              );
                            },
                          ),
                        );
                      }),
                      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: '₹ ',
                          prefixIcon: Icon(Icons.currency_rupee),
                          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;
                        },
                      ),
                    ],
                  ),
                ),
              ),
            ),

            // Fixed Footer with Actions
            Container(
              padding: EdgeInsets.all(24.w),
              decoration: BoxDecoration(
                color: Colors.white,
                borderRadius: BorderRadius.only(
                  bottomLeft: Radius.circular(20.r),
                  bottomRight: Radius.circular(20.r),
                ),
                border: Border(
                  top: BorderSide(color: Colors.grey.shade200),
                ),
              ),
              child: 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),
                        ),
                        elevation: 2,
                      ),
                      child: _isLoading
                          ? SizedBox(
                              height: 20.h,
                              width: 20.w,
                              child: const CircularProgressIndicator(
                                strokeWidth: 2,
                                valueColor: AlwaysStoppedAnimation<Color>(Colors.white),
                              ),
                            )
                          : Text(
                              'Add Draw',
                              style: TextStyle(fontSize: 16.sp, fontWeight: FontWeight.w600),
                            ),
                    ),
                  ),
                ],
              ),
            ),
          ],
        ),
      ),
    );
  }
}

