import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';
import 'shared/widgets/draw_verification_widget.dart';
import 'shared/widgets/draw_animation_selector.dart';
import 'interfaces/manager/combined_draw_dialog.dart';
import 'core/models/chit_group.dart';

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

  @override
  State<TestAnimatedDraw> createState() => _TestAnimatedDrawState();
}

class _TestAnimatedDrawState extends State<TestAnimatedDraw> {
  final List<Map<String, dynamic>> _testMembers = [
    {'id': '1', 'name': 'R Rama Krishna Reddy', 'mobile': '9876543210'},
    {'id': '2', 'name': 'K Srinivas Reddy', 'mobile': '9876543211'},
    {'id': '3', 'name': 'Ch Ramchandra Reddy', 'mobile': '9876543212'},
    {'id': '4', 'name': 'B Krishnahari 1', 'mobile': '9876543213'},
    {'id': '5', 'name': 'B Krishnahari 2', 'mobile': '9876543214'},
    {'id': '6', 'name': 'N Paranjyothi 1', 'mobile': '9876543215'},
    {'id': '7', 'name': 'N Paranjyothi 2', 'mobile': '9876543216'},
    {'id': '8', 'name': 'Sharada 1', 'mobile': '9876543217'},
    {'id': '9', 'name': 'Sharada 2', 'mobile': '9876543218'},
    {'id': '10', 'name': 'Ibrahim', 'mobile': '9876543219'},
    {'id': '11', 'name': 'Waheeda Bee', 'mobile': '9876543220'},
    {'id': '12', 'name': 'R Janardhan Reddy', 'mobile': '9876543221'},
    {'id': '13', 'name': 'Shashank 1', 'mobile': '9876543222'},
    {'id': '14', 'name': 'Shashank 2', 'mobile': '9876543223'},
    {'id': '15', 'name': 'S Saritha', 'mobile': '9876543224'},
    {'id': '16', 'name': 'S Rakesh Reddy', 'mobile': '9876543225'},
    {'id': '17', 'name': 'S Rohini (Sony)', 'mobile': '9876543226'},
    {'id': '18', 'name': 'K Shalini', 'mobile': '9876543227'},
    {'id': '19', 'name': 'K Sundeep Reddy', 'mobile': '9876543228'},
    {'id': '20', 'name': 'K Thirupathi Reddy', 'mobile': '9876543229'},
  ];

  String? _winnerId;
  bool _showVerification = false;

  void _onDrawComplete(String winnerId) {
    setState(() {
      _winnerId = winnerId;
      _showVerification = true;
    });
  }


  void _launchFullSimulation() {
    final testGroup = ChitGroup(
      id: 'test-group-1',
      name: 'Om Sri Sai Chit',
      totalValue: 200000,
      monthlyInstallment: 10250,
      durationMonths: 20,
      maxMembers: 20,
      foremanCommissionAmount: 10000,
      drawDate: 15,
      managerId: 'test-manager-1',
      status: 'active',
      startDate: DateTime(2025, 3, 1), // Started in March 2025
      endDate: DateTime(2026, 10, 31), // Ends in October 2026 (20 months)
      createdAt: DateTime(2025, 3, 1),
      updatedAt: DateTime.now(),
    );

    Get.dialog(
      CombinedDrawDialog(
        group: testGroup,
      ),
      barrierDismissible: false,
    );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('Animated Draw Test'),
        backgroundColor: Colors.purple.shade600,
        foregroundColor: Colors.white,
      ),
      body: SingleChildScrollView(
        padding: EdgeInsets.all(20.w),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            // Header
            Container(
              padding: EdgeInsets.all(20.w),
              decoration: BoxDecoration(
                color: Colors.purple.shade50,
                borderRadius: BorderRadius.circular(12.r),
                border: Border.all(color: Colors.purple.shade200),
              ),
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Text(
                    'Animated Draw Simulation Test',
                    style: TextStyle(
                      fontSize: 24.sp,
                      fontWeight: FontWeight.bold,
                      color: Colors.purple.shade800,
                    ),
                  ),
                  SizedBox(height: 8.h),
                  Text(
                    'Test the spinning wheel animation and provably fair draw system',
                    style: TextStyle(
                      fontSize: 16.sp,
                      color: Colors.purple.shade600,
                    ),
                  ),
                ],
              ),
            ),
            SizedBox(height: 24.h),

            // Test Members
            Text(
              'Test Members (${_testMembers.length})',
              style: TextStyle(
                fontSize: 18.sp,
                fontWeight: FontWeight.w600,
                color: Colors.grey.shade800,
              ),
            ),
            SizedBox(height: 12.h),
            Container(
              height: 200.h,
              decoration: BoxDecoration(
                border: Border.all(color: Colors.grey.shade300),
                borderRadius: BorderRadius.circular(8.r),
              ),
              child: ListView.builder(
                itemCount: _testMembers.length,
                itemBuilder: (context, index) {
                  final member = _testMembers[index];
                  return ListTile(
                    leading: CircleAvatar(
                      backgroundColor: Colors.purple.shade100,
                      child: Text(
                        (member['name']?.isNotEmpty == true 
                            ? member['name'].substring(0, 1) 
                            : 'M').toUpperCase(),
                        style: TextStyle(
                          color: Colors.purple.shade700,
                          fontWeight: FontWeight.w600,
                        ),
                      ),
                    ),
                    title: Text(
                      member['name'],
                      style: TextStyle(fontWeight: FontWeight.w500),
                    ),
                    subtitle: Text(member['mobile']),
                    trailing: _winnerId == member['id']
                        ? Icon(Icons.emoji_events, color: Colors.amber.shade600)
                        : null,
                  );
                },
              ),
            ),
            SizedBox(height: 24.h),

            // Animation Selector
            Center(
              child: Column(
                children: [
                  Text(
                    'Choose Your Draw Animation',
                    style: TextStyle(
                      fontSize: 18.sp,
                      fontWeight: FontWeight.w600,
                      color: Colors.grey.shade800,
                    ),
                  ),
                  SizedBox(height: 16.h),
                  DrawAnimationSelector(
                    members: _testMembers,
                    onDrawComplete: _onDrawComplete,
                    serverSeed: 'test_server_seed_123',
                    clientSeed: 'test_client_seed_123',
                    nonce: DateTime.now().millisecondsSinceEpoch,
                  ),
                ],
              ),
            ),
            SizedBox(height: 24.h),

            // Action Buttons
            Row(
              children: [
                Expanded(
                  child: ElevatedButton(
                    onPressed: () {
                      setState(() {
                        _winnerId = null;
                        _showVerification = false;
                      });
                    },
                    style: ElevatedButton.styleFrom(
                      backgroundColor: Colors.orange.shade600,
                      foregroundColor: Colors.white,
                      padding: EdgeInsets.symmetric(vertical: 16.h),
                      shape: RoundedRectangleBorder(
                        borderRadius: BorderRadius.circular(8.r),
                      ),
                    ),
                    child: Text(
                      'Reset Test',
                      style: TextStyle(fontSize: 16.sp),
                    ),
                  ),
                ),
                SizedBox(width: 12.w),
                Expanded(
                  child: ElevatedButton(
                    onPressed: _launchFullSimulation,
                    style: ElevatedButton.styleFrom(
                      backgroundColor: Colors.blue.shade600,
                      foregroundColor: Colors.white,
                      padding: EdgeInsets.symmetric(vertical: 16.h),
                      shape: RoundedRectangleBorder(
                        borderRadius: BorderRadius.circular(8.r),
                      ),
                    ),
                    child: Text(
                      'Full Simulation',
                      style: TextStyle(fontSize: 16.sp),
                    ),
                  ),
                ),
              ],
            ),
            SizedBox(height: 24.h),

            // Verification Widget
            if (_showVerification && _winnerId != null) ...[
              Text(
                'Draw Verification',
                style: TextStyle(
                  fontSize: 18.sp,
                  fontWeight: FontWeight.w600,
                  color: Colors.grey.shade800,
                ),
              ),
              SizedBox(height: 12.h),
              DrawVerificationWidget(
                serverSeed: 'test_server_seed_123',
                serverSeedHash: 'a1b2c3d4e5f6g7h8i9j0k1l2m3n4o5p6q7r8s9t0',
                clientSeed: 'test_client_seed_123',
                nonce: DateTime.now().millisecondsSinceEpoch,
                eligibleMembers: _testMembers,
                winnerId: _winnerId!,
              ),
            ],

            // Instructions
            SizedBox(height: 24.h),
            Container(
              padding: EdgeInsets.all(16.w),
              decoration: BoxDecoration(
                color: Colors.blue.shade50,
                borderRadius: BorderRadius.circular(8.r),
                border: Border.all(color: Colors.blue.shade200),
              ),
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Text(
                    'How to Test:',
                    style: TextStyle(
                      fontSize: 16.sp,
                      fontWeight: FontWeight.w600,
                      color: Colors.blue.shade800,
                    ),
                  ),
                  SizedBox(height: 8.h),
                  Text(
                    '1. Choose your preferred animation type from the options\n'
                    '2. The system automatically recommends the best animation for your group size\n'
                    '3. Click "Start [Animation Type]" to begin the draw\n'
                    '4. Watch the animation as it selects a winner\n'
                    '5. The verification widget will show the provably fair process\n'
                    '6. Use "Full Simulation" to test the complete draw dialog\n'
                    '7. All draws are transparent and verifiable',
                    style: TextStyle(
                      fontSize: 14.sp,
                      color: Colors.blue.shade700,
                      height: 1.4,
                    ),
                  ),
                ],
              ),
            ),
          ],
        ),
      ),
    );
  }
}
