import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:get/get.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import '../../core/models/chit_group.dart';
import '../../core/models/group_member.dart';
import '../../core/services/payment_service.dart';

class RecordPaymentDialog extends StatefulWidget {
  final ChitGroup group;
  final GroupMember? selectedMember;

  const RecordPaymentDialog({
    super.key,
    required this.group,
    this.selectedMember,
  });

  @override
  State<RecordPaymentDialog> createState() => _RecordPaymentDialogState();
}

class _RecordPaymentDialogState extends State<RecordPaymentDialog> {
  final _formKey = GlobalKey<FormState>();
  final _paymentService = Get.put(PaymentService());
  
  // Form controllers
  final _amountController = TextEditingController();
  final _transactionIdController = TextEditingController();
  final _notesController = TextEditingController();
  
  // Form state
  GroupMember? _selectedMember;
  String _paymentMethod = 'upi';
  int _month = DateTime.now().month;
  int _year = DateTime.now().year;
  
  @override
  void initState() {
    super.initState();
    _selectedMember = widget.selectedMember;
    _amountController.text = widget.group.monthlyInstallment.toStringAsFixed(0);
  }
  
  @override
  void dispose() {
    _amountController.dispose();
    _transactionIdController.dispose();
    _notesController.dispose();
    super.dispose();
  }
  
  @override
  Widget build(BuildContext context) {
    return Dialog(
      shape: RoundedRectangleBorder(
        borderRadius: BorderRadius.circular(16.r),
      ),
      child: Container(
        width: double.infinity,
        constraints: BoxConstraints(
          maxWidth: 500.w,
          maxHeight: 0.9.sh,
        ),
        child: Column(
          mainAxisSize: MainAxisSize.min,
          children: [
            // Header
            Container(
              padding: EdgeInsets.all(20.w),
              decoration: BoxDecoration(
                color: Colors.green.shade50,
                borderRadius: BorderRadius.only(
                  topLeft: Radius.circular(16.r),
                  topRight: Radius.circular(16.r),
                ),
              ),
              child: Row(
                children: [
                  Container(
                    padding: EdgeInsets.all(8.w),
                    decoration: BoxDecoration(
                      color: Colors.green.shade600.withOpacity(0.1),
                      borderRadius: BorderRadius.circular(8.r),
                    ),
                    child: Icon(
                      Icons.payment,
                      color: Colors.green.shade600,
                      size: 24.w,
                    ),
                  ),
                  SizedBox(width: 12.w),
                  Expanded(
                    child: Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        Text(
                          'Record Payment',
                          style: TextStyle(
                            fontSize: 18.sp,
                            fontWeight: FontWeight.w600,
                            color: Colors.green.shade700,
                          ),
                        ),
                        Text(
                          widget.group.name,
                          style: TextStyle(
                            fontSize: 14.sp,
                            color: Colors.green.shade600,
                          ),
                          overflow: TextOverflow.ellipsis,
                        ),
                      ],
                    ),
                  ),
                  IconButton(
                    onPressed: () => Navigator.of(context).pop(),
                    icon: Icon(
                      Icons.close,
                      size: 24.w,
                      color: Colors.grey.shade600,
                    ),
                  ),
                ],
              ),
            ),
            
            // Form
            Flexible(
              child: SingleChildScrollView(
                padding: EdgeInsets.all(20.w),
                child: Form(
                  key: _formKey,
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      // Member Selection
                      Text(
                        'Select Member',
                        style: TextStyle(
                          fontSize: 16.sp,
                          fontWeight: FontWeight.w600,
                          color: Colors.grey.shade800,
                        ),
                      ),
                      SizedBox(height: 8.h),
                      _buildMemberDropdown(),
                      SizedBox(height: 20.h),
                      
                      // Month and Year
                      Row(
                        children: [
                          Expanded(
                            child: Column(
                              crossAxisAlignment: CrossAxisAlignment.start,
                              children: [
                                Text(
                                  'Month',
                                  style: TextStyle(
                                    fontSize: 16.sp,
                                    fontWeight: FontWeight.w600,
                                    color: Colors.grey.shade800,
                                  ),
                                ),
                                SizedBox(height: 8.h),
                                _buildMonthDropdown(),
                              ],
                            ),
                          ),
                          SizedBox(width: 16.w),
                          Expanded(
                            child: Column(
                              crossAxisAlignment: CrossAxisAlignment.start,
                              children: [
                                Text(
                                  'Year',
                                  style: TextStyle(
                                    fontSize: 16.sp,
                                    fontWeight: FontWeight.w600,
                                    color: Colors.grey.shade800,
                                  ),
                                ),
                                SizedBox(height: 8.h),
                                _buildYearDropdown(),
                              ],
                            ),
                          ),
                        ],
                      ),
                      SizedBox(height: 20.h),
                      
                      // Amount
                      Text(
                        'Amount',
                        style: TextStyle(
                          fontSize: 16.sp,
                          fontWeight: FontWeight.w600,
                          color: Colors.grey.shade800,
                        ),
                      ),
                      SizedBox(height: 8.h),
                      TextFormField(
                        controller: _amountController,
                        keyboardType: TextInputType.number,
                        inputFormatters: [
                          FilteringTextInputFormatter.allow(RegExp(r'^\d*\.?\d{0,2}')),
                        ],
                        decoration: InputDecoration(
                          hintText: 'Enter payment amount',
                          prefixIcon: Icon(Icons.currency_rupee, size: 20.w),
                          border: OutlineInputBorder(
                            borderRadius: BorderRadius.circular(8.r),
                          ),
                          filled: true,
                          fillColor: Colors.grey.shade50,
                        ),
                        validator: (value) {
                          if (value == null || value.isEmpty) {
                            return 'Please enter payment amount';
                          }
                          final amount = double.tryParse(value);
                          if (amount == null || amount <= 0) {
                            return 'Please enter a valid amount';
                          }
                          return null;
                        },
                      ),
                      SizedBox(height: 20.h),
                      
                      // Payment Method
                      Text(
                        'Payment Method',
                        style: TextStyle(
                          fontSize: 16.sp,
                          fontWeight: FontWeight.w600,
                          color: Colors.grey.shade800,
                        ),
                      ),
                      SizedBox(height: 8.h),
                      _buildPaymentMethodDropdown(),
                      SizedBox(height: 20.h),
                      
                      // Transaction ID (optional)
                      Text(
                        'Transaction ID (Optional)',
                        style: TextStyle(
                          fontSize: 16.sp,
                          fontWeight: FontWeight.w600,
                          color: Colors.grey.shade800,
                        ),
                      ),
                      SizedBox(height: 8.h),
                      TextFormField(
                        controller: _transactionIdController,
                        decoration: InputDecoration(
                          hintText: 'Enter transaction ID',
                          prefixIcon: Icon(Icons.receipt, size: 20.w),
                          border: OutlineInputBorder(
                            borderRadius: BorderRadius.circular(8.r),
                          ),
                          filled: true,
                          fillColor: Colors.grey.shade50,
                        ),
                      ),
                      SizedBox(height: 20.h),
                      
                      // Notes (optional)
                      Text(
                        'Notes (Optional)',
                        style: TextStyle(
                          fontSize: 16.sp,
                          fontWeight: FontWeight.w600,
                          color: Colors.grey.shade800,
                        ),
                      ),
                      SizedBox(height: 8.h),
                      TextFormField(
                        controller: _notesController,
                        maxLines: 3,
                        decoration: InputDecoration(
                          hintText: 'Add any additional notes',
                          border: OutlineInputBorder(
                            borderRadius: BorderRadius.circular(8.r),
                          ),
                          filled: true,
                          fillColor: Colors.grey.shade50,
                        ),
                      ),
                    ],
                  ),
                ),
              ),
            ),
            
            // Actions
            Container(
              padding: EdgeInsets.all(20.w),
              decoration: BoxDecoration(
                border: Border(
                  top: BorderSide(color: Colors.grey.shade200),
                ),
              ),
              child: Row(
                children: [
                  Expanded(
                    child: OutlinedButton(
                      onPressed: () => Navigator.of(context).pop(),
                      style: OutlinedButton.styleFrom(
                        padding: EdgeInsets.symmetric(vertical: 12.h),
                        shape: RoundedRectangleBorder(
                          borderRadius: BorderRadius.circular(8.r),
                        ),
                      ),
                      child: Text(
                        'Cancel',
                        style: TextStyle(fontSize: 16.sp),
                      ),
                    ),
                  ),
                  SizedBox(width: 12.w),
                  Expanded(
                    flex: 2,
                    child: Obx(() => ElevatedButton(
                      onPressed: _paymentService.isLoading ? null : _recordPayment,
                      style: ElevatedButton.styleFrom(
                        backgroundColor: Colors.green.shade600,
                        foregroundColor: Colors.white,
                        padding: EdgeInsets.symmetric(vertical: 12.h),
                        shape: RoundedRectangleBorder(
                          borderRadius: BorderRadius.circular(8.r),
                        ),
                      ),
                      child: _paymentService.isLoading
                          ? SizedBox(
                              height: 20.h,
                              width: 20.w,
                              child: const CircularProgressIndicator(
                                strokeWidth: 2,
                                valueColor: AlwaysStoppedAnimation<Color>(Colors.white),
                              ),
                            )
                          : Text(
                              'Record Payment',
                              style: TextStyle(
                                fontSize: 16.sp,
                                fontWeight: FontWeight.w600,
                              ),
                            ),
                    )),
                  ),
                ],
              ),
            ),
          ],
        ),
      ),
    );
  }
  
  Widget _buildMemberDropdown() {
    return DropdownButtonFormField<GroupMember>(
      value: _selectedMember,
      decoration: InputDecoration(
        hintText: 'Select a member',
        prefixIcon: Icon(Icons.person, size: 20.w),
        border: OutlineInputBorder(
          borderRadius: BorderRadius.circular(8.r),
        ),
        filled: true,
        fillColor: Colors.grey.shade50,
      ),
      items: widget.group.members?.map((member) {
        return DropdownMenuItem<GroupMember>(
          value: member,
          child: Text(
            member.user?.fullName ?? 'Unknown Member',
            style: TextStyle(fontSize: 16.sp),
          ),
        );
      }).toList(),
      onChanged: (value) {
        setState(() {
          _selectedMember = value;
        });
      },
      validator: (value) {
        if (value == null) {
          return 'Please select a member';
        }
        return null;
      },
    );
  }
  
  Widget _buildMonthDropdown() {
    final months = [
      'January', 'February', 'March', 'April', 'May', 'June',
      'July', 'August', 'September', 'October', 'November', 'December'
    ];
    
    return DropdownButtonFormField<int>(
      value: _month,
      decoration: InputDecoration(
        border: OutlineInputBorder(
          borderRadius: BorderRadius.circular(8.r),
        ),
        filled: true,
        fillColor: Colors.grey.shade50,
      ),
      items: List.generate(12, (index) {
        return DropdownMenuItem<int>(
          value: index + 1,
          child: Text(
            months[index],
            style: TextStyle(fontSize: 16.sp),
          ),
        );
      }),
      onChanged: (value) {
        setState(() {
          _month = value!;
        });
      },
    );
  }
  
  Widget _buildYearDropdown() {
    final currentYear = DateTime.now().year;
    final years = List.generate(5, (index) => currentYear - 2 + index);
    
    return DropdownButtonFormField<int>(
      value: _year,
      decoration: InputDecoration(
        border: OutlineInputBorder(
          borderRadius: BorderRadius.circular(8.r),
        ),
        filled: true,
        fillColor: Colors.grey.shade50,
      ),
      items: years.map((year) {
        return DropdownMenuItem<int>(
          value: year,
          child: Text(
            year.toString(),
            style: TextStyle(fontSize: 16.sp),
          ),
        );
      }).toList(),
      onChanged: (value) {
        setState(() {
          _year = value!;
        });
      },
    );
  }
  
  Widget _buildPaymentMethodDropdown() {
    return DropdownButtonFormField<String>(
      value: _paymentMethod,
      decoration: InputDecoration(
        prefixIcon: Icon(Icons.payment, size: 20.w),
        border: OutlineInputBorder(
          borderRadius: BorderRadius.circular(8.r),
        ),
        filled: true,
        fillColor: Colors.grey.shade50,
      ),
      items: _paymentService.paymentMethods.map((method) {
        return DropdownMenuItem<String>(
          value: method,
          child: Text(
            _paymentService.getPaymentMethodLabel(method),
            style: TextStyle(fontSize: 16.sp),
          ),
        );
      }).toList(),
      onChanged: (value) {
        setState(() {
          _paymentMethod = value!;
        });
      },
    );
  }
  
  Future<void> _recordPayment() async {
    if (!_formKey.currentState!.validate()) return;
    
    if (_selectedMember == null) {
      Get.snackbar(
        'Error',
        'Please select a member',
        backgroundColor: Colors.red.shade100,
        colorText: Colors.red.shade800,
      );
      return;
    }
    
    final amount = double.parse(_amountController.text);
    
    final success = await _paymentService.recordPayment(
      groupId: widget.group.id,
      userId: _selectedMember!.userId,
      month: _month,
      year: _year,
      amount: amount,
      paymentMethod: _paymentMethod,
      transactionId: _transactionIdController.text.isNotEmpty 
          ? _transactionIdController.text 
          : null,
      notes: _notesController.text.isNotEmpty 
          ? _notesController.text 
          : null,
    );
    
    if (success) {
      Get.snackbar(
        'Success',
        'Payment recorded successfully',
        backgroundColor: Colors.green.shade100,
        colorText: Colors.green.shade800,
      );
      Navigator.of(context).pop(true);
    } else {
      Get.snackbar(
        'Error',
        _paymentService.error,
        backgroundColor: Colors.red.shade100,
        colorText: Colors.red.shade800,
      );
    }
  }
}
