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/utils/snackbar_util.dart';
import '../../shared/widgets/dynamic_chit_calculator.dart';

class CreateGroupPage extends StatefulWidget {
  const CreateGroupPage({super.key});

  @override
  State<CreateGroupPage> createState() => _CreateGroupPageState();
}

class _CreateGroupPageState extends State<CreateGroupPage> {
  final _formKey = GlobalKey<FormState>();
  final _nameController = TextEditingController();
  final _totalValueController = TextEditingController();
  final _monthlyContributionController = TextEditingController();
  final _durationMonthsController = TextEditingController();
  final _maxMembersController = TextEditingController();
  final _monthlyCommissionController = TextEditingController();
  final _drawDateController = TextEditingController();
  
  int _currentStep = 0;
  bool _isSubmitting = false;

  @override
  void initState() {
    super.initState();
    _drawDateController.text = '15'; // Default draw date
    _monthlyCommissionController.text = '250'; // Default commission
  }

  @override
  void dispose() {
    _nameController.dispose();
    _totalValueController.dispose();
    _monthlyContributionController.dispose();
    _durationMonthsController.dispose();
    _maxMembersController.dispose();
    _monthlyCommissionController.dispose();
    _drawDateController.dispose();
    super.dispose();
  }

  void _calculateMonthlyPayment() {
    // Rebuild to update preview whenever values change
    setState(() {});
  }

  Future<void> _createGroup() async {
    if (!_formKey.currentState!.validate()) return;

    setState(() => _isSubmitting = true);

    try {
      final contribution = double.parse(_monthlyContributionController.text);
      final commission = double.parse(_monthlyCommissionController.text);
      final monthlyPayment = contribution + commission;
      
      final groupData = {
        'name': _nameController.text.trim(),
        'total_value': double.parse(_totalValueController.text),
        'monthly_installment': monthlyPayment,
        'duration_months': int.parse(_durationMonthsController.text),
        'max_members': int.parse(_maxMembersController.text),
        'foreman_commission_amount': commission,
        'foreman_commission_type': 'fixed',
        'draw_date': int.parse(_drawDateController.text),
      };

      final success = await ChitGroupService.to.createChitGroup(groupData);
      
      if (success) {
        Get.back(); // Go back to previous screen
        SnackbarUtil.showSuccess(
          'Chit group created successfully!',
          title: 'Success',
        );
      }
    } catch (e) {
      SnackbarUtil.showError(
        'Failed to create chit group. Please try again.',
        title: 'Error',
      );
    } finally {
      setState(() => _isSubmitting = false);
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('Create New Chit Fund Group'),
        backgroundColor: Colors.green.shade600,
        foregroundColor: Colors.white,
      ),
      body: Form(
        key: _formKey,
        child: Stepper(
          currentStep: _currentStep,
          onStepContinue: () {
            if (_currentStep < 2) {
              setState(() => _currentStep++);
            } else {
              _createGroup();
            }
          },
          onStepCancel: () {
            if (_currentStep > 0) {
              setState(() => _currentStep--);
            } else {
              Get.back();
            }
          },
          controlsBuilder: (context, details) {
            return Padding(
              padding: EdgeInsets.only(top: 20.h),
              child: Row(
                children: [
                  ElevatedButton(
                    onPressed: _isSubmitting ? null : details.onStepContinue,
                    style: ElevatedButton.styleFrom(
                      backgroundColor: Colors.green.shade600,
                      foregroundColor: Colors.white,
                      padding: EdgeInsets.symmetric(horizontal: 32.w, vertical: 12.h),
                    ),
                    child: _isSubmitting && _currentStep == 2
                        ? SizedBox(
                            width: 20.w,
                            height: 20.h,
                            child: const CircularProgressIndicator(
                              strokeWidth: 2,
                              valueColor: AlwaysStoppedAnimation<Color>(Colors.white),
                            ),
                          )
                        : Text(
                            _currentStep == 2 ? 'Create Group' : 'Continue',
                            style: TextStyle(fontSize: 16.sp),
                          ),
                  ),
                  SizedBox(width: 12.w),
                  OutlinedButton(
                    onPressed: _isSubmitting ? null : details.onStepCancel,
                    style: OutlinedButton.styleFrom(
                      padding: EdgeInsets.symmetric(horizontal: 32.w, vertical: 12.h),
                    ),
                    child: Text(
                      _currentStep == 0 ? 'Cancel' : 'Back',
                      style: TextStyle(fontSize: 16.sp),
                    ),
                  ),
                ],
              ),
            );
          },
          steps: [
            // Step 1: Basic Information
            Step(
              title: const Text('Basic Information'),
              content: _buildBasicInfoStep(),
              isActive: _currentStep >= 0,
              state: _currentStep > 0 ? StepState.complete : StepState.indexed,
            ),

            // Step 2: Financial Details
            Step(
              title: const Text('Financial Details'),
              content: _buildFinancialDetailsStep(),
              isActive: _currentStep >= 1,
              state: _currentStep > 1 ? StepState.complete : StepState.indexed,
            ),

            // Step 3: Review & Schedule
            Step(
              title: const Text('Review & Schedule'),
              content: _buildReviewStep(),
              isActive: _currentStep >= 2,
              state: StepState.indexed,
            ),
          ],
        ),
      ),
    );
  }

  Widget _buildBasicInfoStep() {
    return Column(
      children: [
        TextFormField(
          controller: _nameController,
          decoration: InputDecoration(
            labelText: 'Chit Fund Name',
            hintText: 'e.g., Family Chit Fund',
            prefixIcon: const Icon(Icons.group),
            border: OutlineInputBorder(
              borderRadius: BorderRadius.circular(12.r),
            ),
          ),
          validator: (value) {
            if (value == null || value.trim().isEmpty) {
              return 'Please enter a name';
            }
            if (value.trim().length < 3) {
              return 'Name must be at least 3 characters';
            }
            return null;
          },
        ),
        SizedBox(height: 20.h),

        Row(
          children: [
            Expanded(
              child: TextFormField(
                controller: _durationMonthsController,
                decoration: InputDecoration(
                  labelText: 'Duration (Months)',
                  hintText: 'e.g., 20',
                  prefixIcon: const Icon(Icons.calendar_today),
                  border: OutlineInputBorder(
                    borderRadius: BorderRadius.circular(12.r),
                  ),
                ),
                keyboardType: TextInputType.number,
                onChanged: (_) => _calculateMonthlyPayment(),
                validator: (value) {
                  if (value == null || value.isEmpty) {
                    return 'Required';
                  }
                  final months = int.tryParse(value);
                  if (months == null || months < 6 || months > 60) {
                    return '6-60 months';
                  }
                  return null;
                },
              ),
            ),
            SizedBox(width: 16.w),
            Expanded(
              child: TextFormField(
                controller: _maxMembersController,
                decoration: InputDecoration(
                  labelText: 'Max Members',
                  hintText: 'e.g., 20',
                  prefixIcon: const Icon(Icons.people),
                  border: OutlineInputBorder(
                    borderRadius: BorderRadius.circular(12.r),
                  ),
                ),
                keyboardType: TextInputType.number,
                validator: (value) {
                  if (value == null || value.isEmpty) {
                    return 'Required';
                  }
                  final members = int.tryParse(value);
                  if (members == null || members < 2 || members > 100) {
                    return '2-100 members';
                  }
                  return null;
                },
              ),
            ),
          ],
        ),
        SizedBox(height: 20.h),

        TextFormField(
          controller: _drawDateController,
          decoration: InputDecoration(
            labelText: 'Draw Date (Day of Month)',
            hintText: 'e.g., 15',
            prefixIcon: const Icon(Icons.casino),
            helperText: 'Day of month for lottery draw (1-31)',
            border: OutlineInputBorder(
              borderRadius: BorderRadius.circular(12.r),
            ),
          ),
          keyboardType: TextInputType.number,
          validator: (value) {
            if (value == null || value.isEmpty) {
              return 'Required';
            }
            final day = int.tryParse(value);
            if (day == null || day < 1 || day > 31) {
              return '1-31';
            }
            return null;
          },
        ),
      ],
    );
  }

  Widget _buildFinancialDetailsStep() {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        TextFormField(
          controller: _totalValueController,
          decoration: InputDecoration(
            labelText: 'Fixed Target Value (Chit Value)',
            hintText: 'e.g., 200000',
            prefixIcon: const Icon(Icons.currency_rupee),
            helperText: 'Fixed target value of the chit fund',
            border: OutlineInputBorder(
              borderRadius: BorderRadius.circular(12.r),
            ),
          ),
          keyboardType: TextInputType.number,
          onChanged: (_) => _calculateMonthlyPayment(),
          validator: (value) {
            if (value == null || value.isEmpty) {
              return 'Required';
            }
            final amount = double.tryParse(value);
            if (amount == null || amount < 1000) {
              return 'Min ₹1,000';
            }
            return null;
          },
        ),
        SizedBox(height: 20.h),

        TextFormField(
          controller: _monthlyContributionController,
          decoration: InputDecoration(
            labelText: 'Monthly Contribution (Principal)',
            hintText: 'e.g., 10000',
            prefixIcon: const Icon(Icons.payment),
            helperText: 'Amount each member contributes monthly',
            border: OutlineInputBorder(
              borderRadius: BorderRadius.circular(12.r),
            ),
          ),
          keyboardType: TextInputType.number,
          onChanged: (_) => _calculateMonthlyPayment(),
          validator: (value) {
            if (value == null || value.isEmpty) {
              return 'Required';
            }
            final amount = double.tryParse(value);
            if (amount == null || amount < 100) {
              return 'Min ₹100';
            }
            return null;
          },
        ),
        SizedBox(height: 20.h),

        Row(
          children: [
            Expanded(
              child: TextFormField(
                controller: _monthlyCommissionController,
                decoration: InputDecoration(
                  labelText: 'Monthly Commission/Fee',
                  hintText: 'e.g., 250',
                  prefixIcon: const Icon(Icons.percent),
                  helperText: 'Manager commission per month',
                  border: OutlineInputBorder(
                    borderRadius: BorderRadius.circular(12.r),
                  ),
                ),
                keyboardType: TextInputType.number,
                onChanged: (_) => _calculateMonthlyPayment(),
                validator: (value) {
                  if (value == null || value.isEmpty) {
                    return 'Required';
                  }
                  final amount = double.tryParse(value);
                  if (amount == null || amount < 0) {
                    return 'Invalid';
                  }
                  return null;
                },
              ),
            ),
          ],
        ),
        SizedBox(height: 20.h),

        // Calculated monthly payment display
        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: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Text(
                'Monthly Payment Breakdown',
                style: TextStyle(
                  fontSize: 14.sp,
                  fontWeight: FontWeight.bold,
                  color: Colors.blue.shade800,
                ),
              ),
              SizedBox(height: 12.h),
              _buildPaymentRow(
                'Monthly Contribution',
                _monthlyContributionController.text.isEmpty 
                    ? '-' 
                    : '₹${_monthlyContributionController.text}',
              ),
              _buildPaymentRow(
                'Monthly Commission',
                _monthlyCommissionController.text.isEmpty 
                    ? '-' 
                    : '₹${_monthlyCommissionController.text}',
              ),
              Divider(height: 16.h, color: Colors.blue.shade300),
              _buildPaymentRow(
                'Total Monthly Payment',
                _getMonthlyPayment(),
                isTotal: true,
              ),
            ],
          ),
        ),
      ],
    );
  }

  Widget _buildReviewStep() {
    final totalValue = double.tryParse(_totalValueController.text) ?? 0;
    final duration = int.tryParse(_durationMonthsController.text) ?? 0;
    final contribution = double.tryParse(_monthlyContributionController.text) ?? 0;
    final commission = double.tryParse(_monthlyCommissionController.text) ?? 0;

    return SingleChildScrollView(
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          // Summary card
          Card(
            elevation: 0,
            color: Colors.green.shade50,
            shape: RoundedRectangleBorder(
              borderRadius: BorderRadius.circular(12.r),
              side: BorderSide(color: Colors.green.shade200),
            ),
            child: Padding(
              padding: EdgeInsets.all(16.w),
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Row(
                    children: [
                      Icon(Icons.check_circle, color: Colors.green.shade600, size: 20.w),
                      SizedBox(width: 8.w),
                      Text(
                        'Group Summary',
                        style: TextStyle(
                          fontSize: 16.sp,
                          fontWeight: FontWeight.bold,
                          color: Colors.green.shade800,
                        ),
                      ),
                    ],
                  ),
                  SizedBox(height: 16.h),
                  _buildSummaryRow('Name', _nameController.text),
                  _buildSummaryRow('Target Value', '₹${_totalValueController.text}'),
                  _buildSummaryRow('Duration', '${_durationMonthsController.text} months'),
                  _buildSummaryRow('Max Members', _maxMembersController.text),
                  _buildSummaryRow('Monthly Payment', _getMonthlyPayment()),
                  _buildSummaryRow('Draw Date', '${_drawDateController.text}th of month'),
                ],
              ),
            ),
          ),
          SizedBox(height: 24.h),

          // Month-wise schedule with dynamic calculator
          Text(
            'Month-wise Payment Schedule',
            style: TextStyle(
              fontSize: 18.sp,
              fontWeight: FontWeight.bold,
              color: Colors.grey.shade800,
            ),
          ),
          SizedBox(height: 12.h),

          DynamicChitCalculator(
            chitValue: totalValue,
            durationMonths: duration,
            subscriptionAmount: contribution,
            commissionAmount: commission,
            onCalculationsChanged: (calcs) {
              // Can use these calculations if needed
              print('Calculations updated: $calcs');
            },
          ),
        ],
      ),
    );
  }

  Widget _buildSummaryRow(String label, String value) {
    return Padding(
      padding: EdgeInsets.symmetric(vertical: 6.h),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        children: [
          Text(
            label,
            style: TextStyle(
              fontSize: 14.sp,
              color: Colors.grey.shade700,
            ),
          ),
          Text(
            value,
            style: TextStyle(
              fontSize: 14.sp,
              fontWeight: FontWeight.w600,
              color: Colors.grey.shade800,
            ),
          ),
        ],
      ),
    );
  }

  Widget _buildPaymentRow(String label, String value, {bool isTotal = false}) {
    return Padding(
      padding: EdgeInsets.symmetric(vertical: 4.h),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        children: [
          Text(
            label,
            style: TextStyle(
              fontSize: 13.sp,
              fontWeight: isTotal ? FontWeight.w600 : FontWeight.normal,
              color: isTotal ? Colors.blue.shade800 : Colors.grey.shade700,
            ),
          ),
          Text(
            value,
            style: TextStyle(
              fontSize: 13.sp,
              fontWeight: FontWeight.w600,
              color: isTotal ? Colors.blue.shade900 : Colors.grey.shade800,
            ),
          ),
        ],
      ),
    );
  }

  String _getMonthlyPayment() {
    final contribution = double.tryParse(_monthlyContributionController.text);
    final commission = double.tryParse(_monthlyCommissionController.text);
    
    if (contribution == null || commission == null) {
      return '-';
    }
    
    final total = contribution + commission;
    return '₹${total.toStringAsFixed(0)}';
  }
}

