import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import '../../core/services/auth_service.dart';
import '../../core/services/notification_service.dart';
import '../../core/utils/snackbar_util.dart';
import '../../shared/widgets/interactive_card.dart';
import '../../shared/widgets/notification_badge.dart';
import '../../features/notifications/notification_center_page.dart';

class MemberDashboard extends StatelessWidget {
  const MemberDashboard({super.key});

  @override
  Widget build(BuildContext context) {
    // Initialize notification service
    if (!Get.isRegistered<NotificationService>()) {
      Get.put(NotificationService());
    }
    
    return Scaffold(
      backgroundColor: Colors.grey.shade50,
      appBar: AppBar(
        title: Text(
          'My Chitfunds',
          style: TextStyle(
            fontSize: 18.sp,
            fontWeight: FontWeight.w600,
          ),
        ),
        backgroundColor: Colors.green.shade600,
        foregroundColor: Colors.white,
        elevation: 2,
        actions: [
          // Notifications with badge
          Obx(() {
            final unreadCount = NotificationService.to.unreadCount.value;
            return IconButton(
              icon: NotificationBadge(
                count: unreadCount,
                child: Icon(Icons.notifications_rounded, size: 24.w),
              ),
              onPressed: () => Get.to(() => const NotificationCenterPage()),
              tooltip: 'Notifications',
            );
          }),
          IconButton(
            icon: Icon(Icons.logout, size: 24.w),
            onPressed: () => _showLogoutDialog(context),
          ),
        ],
      ),
      body: RefreshIndicator(
        onRefresh: () async {
          // TODO: Implement refresh logic
          await Future.delayed(const Duration(seconds: 1));
        },
        child: ListView(
          padding: EdgeInsets.all(12.w),
          children: [
            // Welcome Section
            Container(
              padding: EdgeInsets.all(20.w),
              decoration: BoxDecoration(
                gradient: LinearGradient(
                  colors: [Colors.green.shade50, Colors.green.shade100],
                ),
                borderRadius: BorderRadius.circular(16.r),
                boxShadow: [
                  BoxShadow(
                    color: Colors.green.shade200.withOpacity(0.3),
                    blurRadius: 8,
                    offset: const Offset(0, 2),
                  ),
                ],
              ),
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Row(
                    children: [
                      CircleAvatar(
                        radius: 24.r,
                        backgroundColor: Colors.green.shade600,
                        child: Icon(
                          Icons.person,
                          size: 24.w,
                          color: Colors.white,
                        ),
                      ),
                      SizedBox(width: 12.w),
                      Expanded(
                        child: Obx(() => Text(
                          'Welcome, ${AuthService.to.currentUser.value?.fullName ?? 'Member'}!',
                          style: TextStyle(
                            fontSize: 20.sp,
                            fontWeight: FontWeight.bold,
                            color: Colors.green.shade800,
                          ),
                        )),
                      ),
                    ],
                  ),
                  SizedBox(height: 12.h),
                  Text(
                    'Manage your chit fund investments and track your payments.',
                    style: TextStyle(
                      fontSize: 16.sp,
                      color: Colors.green.shade700,
                    ),
                  ),
                ],
              ),
            ),
            SizedBox(height: 16.h),

            // Payment Due Card
            _buildPaymentDueCard(),
            SizedBox(height: 16.h),

            // My Chitfunds Section
            Text(
              'My Chitfunds',
              style: TextStyle(
                fontSize: 20.sp,
                fontWeight: FontWeight.bold,
                color: Colors.grey.shade800,
              ),
            ),
            SizedBox(height: 12.h),
            _buildGroupCard(
              'Group A',
              '₹1,00,000',
              '20 months',
              '15/20 members',
              '₹5,000',
              'Due: 25th Jan',
              Colors.blue,
            ),
            SizedBox(height: 12.h),
            _buildGroupCard(
              'Group B',
              '₹50,000',
              '10 months',
              '8/10 members',
              '₹5,000',
              'Due: 28th Jan',
              Colors.green,
            ),
            SizedBox(height: 16.h),

            // Recent Activity Section
            Text(
              'Recent Activity',
              style: TextStyle(
                fontSize: 20.sp,
                fontWeight: FontWeight.bold,
                color: Colors.grey.shade800,
              ),
            ),
            SizedBox(height: 12.h),
            ActivityCard(
              title: 'Payment Successful',
              description: '₹5,000 paid for Group A',
              time: '2h ago',
              icon: Icons.payment,
              color: Colors.green.shade600,
            ),
            ActivityCard(
              title: 'Lottery Draw',
              description: 'Draw completed for Group B',
              time: '1d ago',
              icon: Icons.casino,
              color: Colors.orange.shade600,
            ),
            ActivityCard(
              title: 'New Member',
              description: 'John Doe joined Group A',
              time: '3d ago',
              icon: Icons.person_add,
              color: Colors.blue.shade600,
            ),
            SizedBox(height: 16.h),
          ],
        ),
      ),
      bottomNavigationBar: Obx(() {
        final unreadCount = NotificationService.to.unreadCount.value;
        
        return BottomNavigationBar(
          type: BottomNavigationBarType.fixed,
          selectedItemColor: Colors.green.shade600,
          unselectedItemColor: Colors.grey.shade600,
          selectedLabelStyle: TextStyle(fontSize: 12.sp, fontWeight: FontWeight.w600),
          unselectedLabelStyle: TextStyle(fontSize: 12.sp),
          iconSize: 24.w,
          items: [
            const BottomNavigationBarItem(
              icon: Icon(Icons.home),
              label: 'Home',
            ),
            const BottomNavigationBarItem(
              icon: Icon(Icons.payment),
              label: 'Payments',
            ),
            BottomNavigationBarItem(
              icon: NotificationBadge(
                count: unreadCount,
                child: const Icon(Icons.notifications),
              ),
              label: 'Notifications',
            ),
            const BottomNavigationBarItem(
              icon: Icon(Icons.person),
              label: 'Profile',
            ),
          ],
          onTap: (index) {
            if (index == 2) {
              Get.to(() => const NotificationCenterPage());
            } else {
              SnackbarUtil.showInfo('Feature coming soon');
            }
          },
        );
      }),
    );
  }

  Widget _buildPaymentDueCard() {
    return Card(
      elevation: 3,
      shape: RoundedRectangleBorder(
        borderRadius: BorderRadius.circular(16.r),
      ),
      child: Container(
        padding: EdgeInsets.all(20.w),
        decoration: BoxDecoration(
          gradient: LinearGradient(
            colors: [Colors.orange.shade50, Colors.orange.shade100],
          ),
          borderRadius: BorderRadius.circular(16.r),
        ),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Row(
              children: [
                Container(
                  padding: EdgeInsets.all(8.w),
                  decoration: BoxDecoration(
                    color: Colors.orange.shade600.withOpacity(0.1),
                    borderRadius: BorderRadius.circular(12.r),
                  ),
                  child: Icon(
                    Icons.payment,
                    color: Colors.orange.shade700,
                    size: 28.w,
                  ),
                ),
                SizedBox(width: 12.w),
                Text(
                  'Payment Due',
                  style: TextStyle(
                    fontSize: 18.sp,
                    fontWeight: FontWeight.bold,
                    color: Colors.orange.shade700,
                  ),
                ),
              ],
            ),
            SizedBox(height: 16.h),
            Text(
              '₹5,000',
              style: TextStyle(
                fontSize: 28.sp,
                fontWeight: FontWeight.bold,
                color: Colors.orange.shade800,
              ),
            ),
            SizedBox(height: 6.h),
            Text(
              'Due by 25th January 2024',
              style: TextStyle(
                fontSize: 16.sp,
                color: Colors.orange.shade700,
                fontWeight: FontWeight.w500,
              ),
            ),
            SizedBox(height: 20.h),
            SizedBox(
              width: double.infinity,
              height: 48.h,
              child: ElevatedButton(
                onPressed: () {
                  // TODO: Implement payment
                  SnackbarUtil.showInfo(
                    'Payment feature coming soon!',
                    title: 'Coming Soon',
                  );
                },
                style: ElevatedButton.styleFrom(
                  backgroundColor: Colors.orange.shade600,
                  foregroundColor: Colors.white,
                  shape: RoundedRectangleBorder(
                    borderRadius: BorderRadius.circular(12.r),
                  ),
                  elevation: 2,
                ),
                child: Text(
                  'Pay Now',
                  style: TextStyle(
                    fontSize: 16.sp,
                    fontWeight: FontWeight.w600,
                  ),
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }

  Widget _buildGroupCard(
    String name,
    String value,
    String duration,
    String members,
    String installment,
    String dueDate,
    Color color,
  ) {
    return InteractiveCard(
      onTap: () {
        SnackbarUtil.showInfo('Group details page coming soon!');
      },
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: [
              Text(
                name,
                style: TextStyle(
                  fontSize: 20.sp,
                  fontWeight: FontWeight.bold,
                  color: color,
                ),
              ),
              Container(
                padding: EdgeInsets.symmetric(horizontal: 12.w, vertical: 6.h),
                decoration: BoxDecoration(
                  color: color.withOpacity(0.1),
                  borderRadius: BorderRadius.circular(16.r),
                  border: Border.all(color: color, width: 1.5),
                ),
                child: Text(
                  'Active',
                  style: TextStyle(
                    fontSize: 14.sp,
                    color: color,
                    fontWeight: FontWeight.w600,
                  ),
                ),
              ),
            ],
          ),
          SizedBox(height: 16.h),
          Column(
            children: [
              Row(
                children: [
                  Expanded(
                    child: _buildGroupInfo('Total Value', value),
                  ),
                  SizedBox(width: 8.w),
                  Expanded(
                    child: _buildGroupInfo('Duration', duration),
                  ),
                ],
              ),
              SizedBox(height: 12.h),
              Row(
                children: [
                  Expanded(
                    child: _buildGroupInfo('Members', members),
                  ),
                  SizedBox(width: 8.w),
                  Expanded(
                    child: _buildGroupInfo('Installment', installment),
                  ),
                ],
              ),
            ],
          ),
          SizedBox(height: 16.h),
          Container(
            width: double.infinity,
            padding: EdgeInsets.all(12.w),
            decoration: BoxDecoration(
              color: color.withOpacity(0.05),
              borderRadius: BorderRadius.circular(12.r),
              border: Border.all(color: color.withOpacity(0.3)),
            ),
            child: Row(
              children: [
                Icon(
                  Icons.schedule,
                  size: 20.w,
                  color: color,
                ),
                SizedBox(width: 8.w),
                Text(
                  dueDate,
                  style: TextStyle(
                    fontSize: 16.sp,
                    color: color,
                    fontWeight: FontWeight.w600,
                  ),
                ),
              ],
            ),
          ),
        ],
      ),
    );
  }

  Widget _buildGroupInfo(String label, String value) {
    return Container(
      padding: EdgeInsets.all(12.w),
      decoration: BoxDecoration(
        color: Colors.grey.shade50,
        borderRadius: BorderRadius.circular(12.r),
        border: Border.all(color: Colors.grey.shade200),
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Text(
            label,
            style: TextStyle(
              fontSize: 14.sp,
              color: Colors.grey.shade600,
              fontWeight: FontWeight.w500,
            ),
          ),
          SizedBox(height: 6.h),
          Text(
            value,
            style: TextStyle(
              fontSize: 16.sp,
              fontWeight: FontWeight.w600,
              color: Colors.grey.shade800,
            ),
          ),
        ],
      ),
    );
  }


  void _showLogoutDialog(BuildContext context) {
    showDialog(
      context: context,
      builder: (context) => AlertDialog(
        title: const Text('Logout'),
        content: const Text('Are you sure you want to logout?'),
        actions: [
          TextButton(
            onPressed: () => Navigator.of(context).pop(),
            child: const Text('Cancel'),
          ),
          ElevatedButton(
            onPressed: () {
              Navigator.of(context).pop();
              AuthService.to.logout();
            },
            style: ElevatedButton.styleFrom(
              backgroundColor: Colors.red,
              foregroundColor: Colors.white,
            ),
            child: const Text('Logout'),
          ),
        ],
      ),
    );
  }
}
