// import 'package:flutter/material.dart';
// import 'package:flutter_riverpod/flutter_riverpod.dart';
// import 'package:go_router/go_router.dart';
// import 'package:hugeicons/hugeicons.dart';
// import 'package:responsive_grid/responsive_grid.dart';
// import 'package:salespro_admin/Screen/User%20Role%20System/staffs_permisson.dart';
// import 'package:salespro_admin/model/user_role_model.dart';
// import '../../Provider/user_role_provider.dart';
// import '../Widgets/Constant Data/constant.dart';
//
// class UserRoleScreen extends StatefulWidget {
//   const UserRoleScreen({super.key});
//
//   static const String route = '/user_role';
//
//   @override
//   State<UserRoleScreen> createState() => _UserRoleScreenState();
// }
//
// class _UserRoleScreenState extends State<UserRoleScreen> {
//   @override
//   Widget build(BuildContext context) {
//     final theme = Theme.of(context);
//     final screenWidth = MediaQuery.of(context).size.width;
//     return SafeArea(
//       child: Scaffold(
//           backgroundColor: kDarkWhite,
//           body: Consumer(builder: (_, ref, watch) {
//             final customers = ref.watch(userRoleProvider);
//             return customers.when(data: (allCustomerList) {
//               List<UserRoleModel> customerList = allCustomerList;
//               return SingleChildScrollView(
//                 padding: const EdgeInsets.all(16),
//                 child: Column(
//                   crossAxisAlignment: CrossAxisAlignment.start,
//                   children: [
//                     Container(
//                       decoration: BoxDecoration(borderRadius: BorderRadius.circular(20.0), color: kWhite),
//                       child: Column(
//                         children: [
//                           Padding(
//                             padding: const EdgeInsets.all(10.0),
//                             child: Row(
//                               mainAxisAlignment: MainAxisAlignment.spaceBetween,
//                               children: [
//                                 Flexible(
//                                   child: Text(
//                                     'Role & Permission',
//                                     style: theme.textTheme.titleLarge?.copyWith(fontWeight: FontWeight.w600),
//                                   ),
//                                 ),
//                               ],
//                             ),
//                           ),
//                           const SizedBox(height: 5.0),
//                           const Divider(
//                             thickness: 1.0,
//                             color: kNeutral300,
//                             height: 1,
//                           ),
//                           Padding(
//                             padding: const EdgeInsets.all(8.0),
//                             child: ResponsiveGridRow(
//                                 children: List.generate(customerList.length + 1, (index) {
//                               if (index == 0) {
//                                 return ResponsiveGridCol(
//                                     xs: 12,
//                                     md: 6,
//                                     lg: 4,
//                                     child: Padding(
//                                       padding: const EdgeInsets.all(10.0),
//                                       child: Container(
//                                         height: 92,
//                                         padding: const EdgeInsets.all(12),
//                                         decoration: BoxDecoration(
//                                           color: Colors.white,
//                                           borderRadius: BorderRadius.circular(8),
//                                           boxShadow: [
//                                             BoxShadow(
//                                               color: const Color(0xff171717).withValues(alpha: 0.17),
//                                               blurRadius: 17,
//                                               offset: const Offset(0, 3),
//                                               spreadRadius: -4,
//                                             )
//                                           ],
//                                         ),
//                                         child: Row(
//                                           mainAxisAlignment: MainAxisAlignment.spaceBetween,
//                                           children: [
//                                             Image.asset(
//                                               'images/usr_role_logo.png',
//                                               height: 81,
//                                               width: 66,
//                                             ),
//                                             Flexible(
//                                               child: Column(
//                                                 crossAxisAlignment: CrossAxisAlignment.end,
//                                                 mainAxisAlignment: MainAxisAlignment.end,
//                                                 children: [
//                                                   ElevatedButton(
//                                                     style: ElevatedButton.styleFrom(
//                                                       maximumSize: Size.fromHeight(40),
//                                                     ),
//                                                     onPressed: () => context.go('/add-user-role'),
//                                                     child: const Text('Add New Role'),
//                                                   ),
//                                                   SizedBox(height: 2),
//                                                   Text(
//                                                     'Add role, if it does not exist',
//                                                     style: theme.textTheme.bodyLarge,
//                                                     maxLines: 1,
//                                                     overflow: TextOverflow.ellipsis,
//                                                   ),
//                                                 ],
//                                               ),
//                                             )
//                                           ],
//                                         ),
//                                       ),
//                                     ));
//                               } else {
//                                 final role = customerList[index - 1]; // adjust index
//                                 final customer = customerList[index - 1];
//                                 return ResponsiveGridCol(
//                                     xs: 12,
//                                     md: 6,
//                                     lg: 4,
//                                     child: Padding(
//                                       padding: const EdgeInsets.all(10.0),
//                                       child: Container(
//                                         height: 92,
//                                         alignment: Alignment.center,
//                                         decoration: BoxDecoration(
//                                           color: Colors.white,
//                                           borderRadius: BorderRadius.circular(8),
//                                           boxShadow: [
//                                             BoxShadow(
//                                               color: const Color(0xff171717).withValues(alpha: 0.17),
//                                               blurRadius: 17,
//                                               offset: const Offset(0, 3),
//                                               spreadRadius: -4,
//                                             )
//                                           ],
//                                         ),
//                                         child: ListTile(
//                                           title: Text(
//                                             customerList[index - 1].email.toString(), // use your model field
//                                             style: theme.textTheme.titleLarge?.copyWith(
//                                               fontWeight: FontWeight.bold,
//                                             ),
//                                           ),
//                                           subtitle: Text(
//                                             '${5} Features', // example field
//                                             style: theme.textTheme.bodyLarge?.copyWith(color: kGreyTextColor),
//                                           ),
//                                           trailing: Row(
//                                             mainAxisSize: MainAxisSize.min,
//                                             children: [
//                                               GestureDetector(
//                                                 onTap: () {
//                                                   AddUserRolePermission(userRoleModel: customerList[index]);
//                                                 },
//                                                 child: HugeIcon(icon: HugeIcons.strokeRoundedPencilEdit02, color: kSucessColor),
//                                               ),
//                                               SizedBox(width: 10),
//                                               GestureDetector(
//                                                 onTap: () {},
//                                                 child: HugeIcon(icon: HugeIcons.strokeRoundedDelete03, color: kErrorColor),
//                                               ),
//                                             ],
//                                           ),
//                                         ),
//                                       ),
//                                     ));
//                               }
//                             })),
//                           )
//                         ],
//                       ),
//                     ),
//                   ],
//                 ),
//               );
//             }, error: (e, stack) {
//               print(e.toString());
//               return Center(
//                 child: Text(e.toString()),
//               );
//             }, loading: () {
//               return const Center(
//                 child: CircularProgressIndicator(),
//               );
//             });
//           })),
//     );
//   }
// }

import 'package:firebase_auth/firebase_auth.dart';
import 'package:firebase_database/firebase_database.dart';
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:go_router/go_router.dart';
import 'package:hugeicons/hugeicons.dart';
import 'package:responsive_grid/responsive_grid.dart';
import 'package:salespro_admin/model/user_role_model.dart';

import '../../Provider/user_role_provider.dart';
import '../Widgets/Constant Data/constant.dart';

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

  static const String route = '/user_role';

  @override
  State<UserRoleScreen> createState() => _UserRoleScreenState();
}

class _UserRoleScreenState extends State<UserRoleScreen> {
  @override
  Widget build(BuildContext context) {
    final theme = Theme.of(context);
    return SafeArea(
      child: Scaffold(
        backgroundColor: kDarkWhite,
        body: Consumer(
          builder: (_, ref, __) {
            final userRolesAsync = ref.watch(userRoleProvider);

            return userRolesAsync.when(
              data: (userRoles) {
                // if (userRoles.isEmpty) {
                //   return Center(
                //     child: Text(
                //       'No user roles found',
                //       style: theme.textTheme.titleMedium,
                //     ),
                //   );
                // }

                return SingleChildScrollView(
                  padding: const EdgeInsets.all(16),
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      Container(
                        decoration: BoxDecoration(
                            borderRadius: BorderRadius.circular(20.0), color: kWhite),
                        child: Column(
                          children: [
                            Padding(
                              padding: const EdgeInsets.all(10.0),
                              child: Row(
                                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                                children: [
                                  Flexible(
                                    child: Text('Role & Permission',
                                        style: theme.textTheme.titleLarge
                                            ?.copyWith(fontWeight: FontWeight.w600)),
                                  ),
                                ],
                              ),
                            ),
                            const SizedBox(height: 5.0),
                            const Divider(thickness: 1.0, color: kNeutral300, height: 1),
                            Padding(
                              padding: const EdgeInsets.all(8.0),
                              child: ResponsiveGridRow(
                                children: [
                                  // Add New Role Card
                                  ResponsiveGridCol(
                                    xs: 12,
                                    md: 6,
                                    lg: 4,
                                    child: Padding(
                                      padding: const EdgeInsets.all(10.0),
                                      child: Container(
                                        height: 92,
                                        padding: const EdgeInsets.all(12),
                                        decoration: BoxDecoration(
                                          color: Colors.white,
                                          borderRadius: BorderRadius.circular(8),
                                          boxShadow: [
                                            BoxShadow(
                                                color: const Color(0xff171717)
                                                    .withValues(alpha: 0.17),
                                                blurRadius: 17,
                                                offset: const Offset(0, 3),
                                                spreadRadius: -4),
                                          ],
                                        ),
                                        child: Row(
                                          mainAxisAlignment: MainAxisAlignment.spaceBetween,
                                          children: [
                                            Image.asset('images/usr_role_logo.png',
                                                height: 81, width: 66),
                                            Flexible(
                                              child: Column(
                                                crossAxisAlignment: CrossAxisAlignment.end,
                                                mainAxisAlignment: MainAxisAlignment.end,
                                                children: [
                                                  ElevatedButton(
                                                    style: ElevatedButton.styleFrom(
                                                        maximumSize: Size.fromHeight(40)),
                                                    onPressed: () => context.go('/add-user-role',
                                                        extra: userRoles),
                                                    child: const Text('Add New Role'),
                                                  ),
                                                  const SizedBox(height: 2),
                                                  Text('Add role, if it does not exist',
                                                      style: theme.textTheme.bodyLarge,
                                                      maxLines: 1,
                                                      overflow: TextOverflow.ellipsis),
                                                ],
                                              ),
                                            ),
                                          ],
                                        ),
                                      ),
                                    ),
                                  ),
                                  // User Role List Items
                                  ...userRoles.map((userRole) {
                                    final featureCount = _countPermissions(userRole);
                                    return ResponsiveGridCol(
                                      xs: 12,
                                      md: 6,
                                      lg: 4,
                                      child: Padding(
                                        padding: const EdgeInsets.all(10.0),
                                        child: Container(
                                          height: 92,
                                          alignment: Alignment.center,
                                          decoration: BoxDecoration(
                                            color: Colors.white,
                                            borderRadius: BorderRadius.circular(8),
                                            boxShadow: [
                                              BoxShadow(
                                                  color: const Color(0xff171717)
                                                      .withValues(alpha: 0.17),
                                                  blurRadius: 17,
                                                  offset: const Offset(0, 3),
                                                  spreadRadius: -4),
                                            ],
                                          ),
                                          child: ListTile(
                                            title: Text(userRole.userEmail ?? 'No title',
                                                style: theme.textTheme.titleLarge
                                                    ?.copyWith(fontWeight: FontWeight.bold)),
                                            subtitle: Text('$featureCount Features',
                                                style: theme.textTheme.bodyLarge
                                                    ?.copyWith(color: kGreyTextColor)),
                                            trailing: Row(
                                              mainAxisSize: MainAxisSize.min,
                                              children: [
                                                GestureDetector(
                                                  onTap: () {
                                                    context.go('/add-user-role', extra: userRole);
                                                  },
                                                  child: HugeIcon(
                                                      icon: HugeIcons.strokeRoundedPencilEdit02,
                                                      color: kSucessColor),
                                                ),
                                                const SizedBox(width: 10),
                                                GestureDetector(
                                                  onTap: () => _deleteUserRole(ref, userRole),
                                                  child: HugeIcon(
                                                      icon: HugeIcons.strokeRoundedDelete03,
                                                      color: kErrorColor),
                                                ),
                                              ],
                                            ),
                                          ),
                                        ),
                                      ),
                                    );
                                  }).toList(),
                                ],
                              ),
                            ),
                          ],
                        ),
                      ),
                    ],
                  ),
                );
              },
              error: (error, stack) {
                return Center(
                  child: Text('Error loading user roles: ${error.toString()}',
                      style: theme.textTheme.bodyLarge?.copyWith(color: kErrorColor)),
                );
              },
              loading: () => const Center(child: CircularProgressIndicator()),
            );
          },
        ),
      ),
    );
  }

  int _countPermissions(UserRoleModel userRole) {
    // Implement logic to count actual permissions
    // This is a simplified version - adjust based on your actual permission structure
    int count = 0;
    if (userRole.dashboardRead ?? false) count++;
    if (userRole.posSaleRead ?? false) count++;
    if (userRole.productRead ?? false) count++;
    // Add all other permissions...
    return count;
  }

  Future<void> _deleteUserRole(WidgetRef ref, UserRoleModel userRole) async {
    final confirmed = await showDialog<bool>(
      context: context,
      builder: (context) => AlertDialog(
        title: const Text('Confirm Delete'),
        content: Text('Are you sure you want to delete ${userRole.userEmail}?'),
        actions: [
          TextButton(onPressed: () => Navigator.pop(context, false), child: const Text('Cancel')),
          TextButton(
            onPressed: () => Navigator.pop(context, true),
            child: const Text('Delete', style: TextStyle(color: Colors.red)),
          ),
        ],
      ),
    );

    if (confirmed == true) {
      try {
        // Implement your delete logic here
        // Example:
        final currentUser = FirebaseAuth.instance.currentUser;
        if (currentUser == null || currentUser.uid.isEmpty) {
          throw Exception('User not authenticated');
        }
        final userPath = "${currentUser.uid}/User Role/${userRole.id}";
        final adminPath = "Admin Panel/User Role/${userRole.id}";
        await FirebaseDatabase.instance.ref(userPath).remove();
        await FirebaseDatabase.instance.ref(adminPath).remove();
        ref.refresh(userRoleProvider);
        ScaffoldMessenger.of(context)
            .showSnackBar(SnackBar(content: Text('${userRole.userEmail} deleted successfully')));
      } catch (e) {
        ScaffoldMessenger.of(context)
            .showSnackBar(SnackBar(content: Text('Failed to delete: ${e.toString()}')));
      }
    }
  }
}
