import 'package:firebase_auth/firebase_auth.dart';
import 'package:firebase_database/firebase_database.dart';
import 'package:flutter/material.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:flutter_feather_icons/flutter_feather_icons.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:go_router/go_router.dart';
import 'package:nb_utils/nb_utils.dart';
import 'package:responsive_grid/responsive_grid.dart';
import 'package:salespro_admin/generated/l10n.dart' as lang;

import '../../Provider/user_role_provider.dart';
import '../../model/user_role_model.dart';
import '../HRM/employees/model/employee_model.dart';
import '../HRM/employees/provider/designation_provider.dart';
import '../Widgets/Constant Data/constant.dart';

class AddUserRolePermission extends ConsumerStatefulWidget {
  const AddUserRolePermission({super.key, this.userRoleModel, this.users});

  final UserRoleModel? userRoleModel;
  final List<UserRoleModel>? users;

  static const String route = '/user_role';

  @override
  ConsumerState<AddUserRolePermission> createState() => _AddUserRolePermissionState();
}

class _AddUserRolePermissionState extends ConsumerState<AddUserRolePermission> {
  final GlobalKey<FormState> _formKey = GlobalKey<FormState>();
  final ScrollController _horizontalScroll = ScrollController();
  final TextEditingController loginUserController = TextEditingController();
  final TextEditingController passwordController = TextEditingController();
  final TextEditingController titleController = TextEditingController();

  bool? isTapped;
  EmployeeModel? selectedEmployee;
  final selectedEmployeeProvider = StateProvider<EmployeeModel?>((ref) => null);
  bool hidePassword = true;
  String adminRoleKey = '';
  String userRoleKey = '';

  List<Permission> permissions = [
    Permission(title: 'Dashboard'),
    Permission(title: 'Pos Sale'),
    Permission(title: 'Inventory Sales'),
    Permission(title: 'Sale List'),
    Permission(title: 'Sale Return'),
    Permission(title: 'Quotation List'),
    Permission(title: 'Purchase'),
    Permission(title: 'Purchase List'),
    Permission(title: 'Purchase Return'),
    Permission(title: 'Product'),
    Permission(title: 'Low Stock'),
    Permission(title: 'Expired'),
    Permission(title: 'Categories'),
    Permission(title: 'Brand'),
    Permission(title: 'Unit'),
    Permission(title: 'Warehouse'),
    Permission(title: 'Supplier List'),
    Permission(title: 'Customer List'),
    Permission(title: 'Due List'),
    Permission(title: 'Ledger'),
    Permission(title: 'Profit/ Loss'),
    Permission(title: 'Payment Type'),
    Permission(title: 'Expense'),
    Permission(title: 'Expense Category'),
    Permission(title: 'Income'),
    Permission(title: 'Income Category'),
    Permission(title: 'Transaction'),
    Permission(title: 'All Reports'),
    Permission(title: 'WhatsApp Marketing'),
    Permission(title: 'Stock List'),
    Permission(title: 'Subscription'),
    Permission(title: 'User Role'),
    Permission(title: 'Tax Rate'),
    Permission(title: 'HRM'),
  ];

  bool dashboardRead = false;
  bool posSaleRead = false;
  bool posSaleCreate = false;
  bool posSaleDelete = false;
  bool posSaleUpdate = false;
  bool inventorySaleRead = false;
  bool inventorySaleCreate = false;
  bool inventorySaleUpdate = false;
  bool inventorySaleDelete = false;
  bool saleListRead = false;
  bool saleListCreate = false;
  bool saleListUpdate = false;
  bool saleListDelete = false;
  bool saleReturnRead = false;
  bool saleReturnCreate = false;
  bool saleReturnUpdate = false;
  bool saleReturnDelete = false;
  bool quotationListRead = false;
  bool quotationListCreate = false;
  bool quotationListUpdate = false;
  bool quotationListDelete = false;
  bool purchaseRead = false;
  bool purchaseCreate = false;
  bool purchaseUpdate = false;
  bool purchaseDelete = false;
  bool purchaseReturnRead = false;
  bool purchaseReturnCreate = false;
  bool purchaseReturnUpdate = false;
  bool purchaseReturnDelete = false;
  bool productRead = false;
  bool productCreate = false;
  bool productUpdate = false;
  bool productDelete = false;
  bool lowStockRead = false;
  bool lowStockCreate = false;
  bool lowStockUpdate = false;
  bool lowStockDelete = false;
  bool expiredRead = false;
  bool expiredCreate = false;
  bool expiredUpdate = false;
  bool expiredDelete = false;
  bool categoriesRead = false;
  bool categoriesCreate = false;
  bool categoriesUpdate = false;
  bool categoriesDelete = false;
  bool brandRead = false;
  bool brandCreate = false;
  bool brandUpdate = false;
  bool brandDelete = false;
  bool unitRead = false;
  bool unitCreate = false;
  bool unitUpdate = false;
  bool unitDelete = false;
  bool wareHouseRead = false;
  bool wareHouseCreate = false;
  bool wareHouseUpdate = false;
  bool wareHouseDelete = false;
  bool supplierListRead = false;
  bool supplierListCreate = false;
  bool supplierListUpdate = false;
  bool supplierListDelete = false;
  bool customerListRead = false;
  bool customerListCreate = false;
  bool customerListUpdate = false;
  bool customerListDelete = false;
  bool dueListRead = false;
  bool dueListCreate = false;
  bool dueListUpdate = false;
  bool dueListDelete = false;
  bool ledgerRead = false;
  bool ledgerCreate = false;
  bool ledgerUpdate = false;
  bool ledgerDelete = false;
  bool lossProfitRead = false;
  bool lossProfitCreate = false;
  bool lossProfitUpdate = false;
  bool lossProfitDelete = false;
  bool paymentTypeRead = false;
  bool paymentTypeCreate = false;
  bool paymentTypeUpdate = false;
  bool paymentTypeDelete = false;
  bool expenseRead = false;
  bool expenseCreate = false;
  bool expenseUpdate = false;
  bool expenseDelete = false;
  bool expenseCategoryRead = false;
  bool expenseCategoryCreate = false;
  bool expenseCategoryUpdate = false;
  bool expenseCategoryDelete = false;
  bool incomeRead = false;
  bool incomeCreate = false;
  bool incomeUpdate = false;
  bool incomeDelete = false;
  bool incomeCategoryRead = false;
  bool incomeCategoryCreate = false;
  bool incomeCategoryUpdate = false;
  bool incomeCategoryDelete = false;
  bool transactionRead = false;
  bool transactionCreate = false;
  bool transactionUpdate = false;
  bool transactionDelete = false;
  bool allReportsRead = false;
  bool allReportsCreate = false;
  bool allReportsUpdate = false;
  bool allReportsDelete = false;
  bool whatsAppMarketingRead = false;
  bool whatsAppMarketingCreate = false;
  bool whatsAppMarketingUpdate = false;
  bool whatsAppMarketingDelete = false;
  bool stockListRead = false;
  bool stockListCreate = false;
  bool stockListUpdate = false;
  bool stockListDelete = false;
  bool subscriptionRead = false;
  bool subscriptionCreate = false;
  bool subscriptionUpdate = false;
  bool subscriptionDelete = false;
  bool userRoleRead = false;
  bool userRoleCreate = false;
  bool userRoleUpdate = false;
  bool userRoleDelete = false;
  bool taxRateRead = false;
  bool taxRateCreate = false;
  bool taxRateUpdate = false;
  bool taxRateDelete = false;
  bool hrmRead = false;
  bool hrmCreate = false;
  bool hrmUpdate = false;
  bool hrmDelete = false;

  @override
  void initState() {
    super.initState();
    if (widget.userRoleModel != null) {
      setEditData();
    }
  }

  void setEditData() {
    loginUserController.text = widget.userRoleModel?.userEmail ?? '';
    for (var data in permissions) {
      if (data.title == "Dashboard") {
        data.read = widget.userRoleModel?.dashboardRead ?? false;
      } else if (data.title == "Pos Sale") {
        data.read = widget.userRoleModel?.posSaleRead ?? false;
        data.create = widget.userRoleModel?.posSaleCreate ?? false;
        data.update = widget.userRoleModel?.posSaleUpdate ?? false;
        data.delete = widget.userRoleModel?.posSaleDelete ?? false;
      } else if (data.title == "Inventory Sales") {
        data.read = widget.userRoleModel?.inventorySaleRead ?? false;
        data.create = widget.userRoleModel?.inventorySaleCreate ?? false;
        data.update = widget.userRoleModel?.inventorySaleUpdate ?? false;
        data.delete = widget.userRoleModel?.inventorySaleDelete ?? false;
      } else if (data.title == "Sale List") {
        data.read = widget.userRoleModel?.saleListRead ?? false;
        data.create = widget.userRoleModel?.saleListCreate ?? false;
        data.update = widget.userRoleModel?.saleListUpdate ?? false;
        data.delete = widget.userRoleModel?.saleListDelete ?? false;
      } else if (data.title == "Sale Return") {
        data.read = widget.userRoleModel?.saleReturnRead ?? false;
        data.create = widget.userRoleModel?.saleReturnCreate ?? false;
        data.update = widget.userRoleModel?.saleReturnUpdate ?? false;
        data.delete = widget.userRoleModel?.saleReturnDelete ?? false;
      } else if (data.title == "Quotation List") {
        data.read = widget.userRoleModel?.quotationListRead ?? false;
        data.create = widget.userRoleModel?.quotationListCreate ?? false;
        data.update = widget.userRoleModel?.quotationListUpdate ?? false;
        data.delete = widget.userRoleModel?.quotationListDelete ?? false;
      } else if (data.title == "Purchase") {
        data.read = widget.userRoleModel?.purchaseRead ?? false;
        data.create = widget.userRoleModel?.purchaseCreate ?? false;
        data.update = widget.userRoleModel?.purchaseUpdate ?? false;
        data.delete = widget.userRoleModel?.purchaseDelete ?? false;
      } else if (data.title == "Purchase List") {
        data.read = widget.userRoleModel?.purchaseRead ?? false;
        data.create = widget.userRoleModel?.purchaseCreate ?? false;
        data.update = widget.userRoleModel?.purchaseUpdate ?? false;
        data.delete = widget.userRoleModel?.purchaseDelete ?? false;
      } else if (data.title == "Purchase Return") {
        print('Purchase Return: ${widget.userRoleModel?.purchaseReturnRead}');
        data.read = widget.userRoleModel?.purchaseReturnRead ?? false;
        data.create = widget.userRoleModel?.purchaseReturnCreate ?? false;
        data.update = widget.userRoleModel?.purchaseReturnUpdate ?? false;
        data.delete = widget.userRoleModel?.purchaseReturnDelete ?? false;
      } else if (data.title == "Product") {
        data.read = widget.userRoleModel?.productRead ?? false;
        data.create = widget.userRoleModel?.productCreate ?? false;
        data.update = widget.userRoleModel?.productUpdate ?? false;
        data.delete = widget.userRoleModel?.productDelete ?? false;
      } else if (data.title == "Low Stock") {
        data.read = widget.userRoleModel?.lowStockRead ?? false;
        data.create = widget.userRoleModel?.lowStockCreate ?? false;
        data.update = widget.userRoleModel?.lowStockUpdate ?? false;
        data.delete = widget.userRoleModel?.lowStockDelete ?? false;
      } else if (data.title == "Expired") {
        data.read = widget.userRoleModel?.expiredRead ?? false;
        data.create = widget.userRoleModel?.expiredCreate ?? false;
        data.update = widget.userRoleModel?.expiredUpdate ?? false;
        data.delete = widget.userRoleModel?.expiredDelete ?? false;
      } else if (data.title == "Categories") {
        data.read = widget.userRoleModel?.categoriesRead ?? false;
        data.create = widget.userRoleModel?.categoriesCreate ?? false;
        data.update = widget.userRoleModel?.categoriesUpdate ?? false;
        data.delete = widget.userRoleModel?.categoriesDelete ?? false;
      } else if (data.title == "Brand") {
        data.read = widget.userRoleModel?.brandRead ?? false;
        data.create = widget.userRoleModel?.brandCreate ?? false;
        data.update = widget.userRoleModel?.brandUpdate ?? false;
        data.delete = widget.userRoleModel?.brandDelete ?? false;
      } else if (data.title == "Unit") {
        data.read = widget.userRoleModel?.unitRead ?? false;
        data.create = widget.userRoleModel?.unitCreate ?? false;
        data.update = widget.userRoleModel?.unitUpdate ?? false;
        data.delete = widget.userRoleModel?.unitDelete ?? false;
      } else if (data.title == "Warehouse") {
        data.read = widget.userRoleModel?.wareHouseRead ?? false;
        data.create = widget.userRoleModel?.wareHouseCreate ?? false;
        data.update = widget.userRoleModel?.wareHouseUpdate ?? false;
        data.delete = widget.userRoleModel?.wareHouseDelete ?? false;
      } else if (data.title == "Supplier List") {
        data.read = widget.userRoleModel?.supplierListRead ?? false;
        data.create = widget.userRoleModel?.supplierListCreate ?? false;
        data.update = widget.userRoleModel?.supplierListUpdate ?? false;
        data.delete = widget.userRoleModel?.supplierListDelete ?? false;
      } else if (data.title == "Customer List") {
        data.read = widget.userRoleModel?.customerListRead ?? false;
        data.create = widget.userRoleModel?.customerListCreate ?? false;
        data.update = widget.userRoleModel?.customerListUpdate ?? false;
        data.delete = widget.userRoleModel?.customerListDelete ?? false;
      } else if (data.title == "Due List") {
        data.read = widget.userRoleModel?.dueListRead ?? false;
        data.create = widget.userRoleModel?.dueListCreate ?? false;
        data.update = widget.userRoleModel?.dueListUpdate ?? false;
        data.delete = widget.userRoleModel?.dueListDelete ?? false;
      } else if (data.title == "Ledger") {
        data.read = widget.userRoleModel?.ledgerRead ?? false;
        data.create = widget.userRoleModel?.ledgerCreate ?? false;
        data.update = widget.userRoleModel?.ledgerUpdate ?? false;
        data.delete = widget.userRoleModel?.ledgerDelete ?? false;
      } else if (data.title == "Profit/ Loss") {
        data.read = widget.userRoleModel?.lossProfitRead ?? false;
        data.create = widget.userRoleModel?.lossProfitCreate ?? false;
        data.update = widget.userRoleModel?.lossProfitUpdate ?? false;
        data.delete = widget.userRoleModel?.lossProfitDelete ?? false;
      } else if (data.title == "Payment Type") {
        data.read = widget.userRoleModel?.paymentTypeRead ?? false;
        data.create = widget.userRoleModel?.paymentTypeCreate ?? false;
        data.update = widget.userRoleModel?.paymentTypeUpdate ?? false;
        data.delete = widget.userRoleModel?.paymentTypeDelete ?? false;
      } else if (data.title == "Expense") {
        data.read = widget.userRoleModel?.expenseRead ?? false;
        data.create = widget.userRoleModel?.expenseCreate ?? false;
        data.update = widget.userRoleModel?.expenseUpdate ?? false;
        data.delete = widget.userRoleModel?.expenseDelete ?? false;
      } else if (data.title == "Expense Category") {
        data.read = widget.userRoleModel?.expenseCategoryRead ?? false;
        data.create = widget.userRoleModel?.expenseCategoryCreate ?? false;
        data.update = widget.userRoleModel?.expenseCategoryUpdate ?? false;
        data.delete = widget.userRoleModel?.expenseCategoryDelete ?? false;
      } else if (data.title == "Income") {
        data.read = widget.userRoleModel?.incomeRead ?? false;
        data.create = widget.userRoleModel?.incomeCreate ?? false;
        data.update = widget.userRoleModel?.incomeUpdate ?? false;
        data.delete = widget.userRoleModel?.incomeDelete ?? false;
      } else if (data.title == "Income Category") {
        data.read = widget.userRoleModel?.incomeCategoryRead ?? false;
        data.create = widget.userRoleModel?.incomeCategoryCreate ?? false;
        data.update = widget.userRoleModel?.incomeCategoryUpdate ?? false;
        data.delete = widget.userRoleModel?.incomeCategoryDelete ?? false;
      } else if (data.title == "Transaction") {
        data.read = widget.userRoleModel?.transactionRead ?? false;
        data.create = widget.userRoleModel?.transactionCreate ?? false;
        data.update = widget.userRoleModel?.transactionUpdate ?? false;
        data.delete = widget.userRoleModel?.transactionDelete ?? false;
      } else if (data.title == "All Reports") {
        data.read = widget.userRoleModel?.allReportsRead ?? false;
        data.create = widget.userRoleModel?.allReportsCreate ?? false;
        data.update = widget.userRoleModel?.allReportsUpdate ?? false;
        data.delete = widget.userRoleModel?.allReportsDelete ?? false;
      } else if (data.title == "WhatsApp Marketing") {
        data.read = widget.userRoleModel?.whatsAppMarketingRead ?? false;
        data.create = widget.userRoleModel?.whatsAppMarketingCreate ?? false;
        data.update = widget.userRoleModel?.whatsAppMarketingUpdate ?? false;
        data.delete = widget.userRoleModel?.whatsAppMarketingDelete ?? false;
      } else if (data.title == "Stock List") {
        data.read = widget.userRoleModel?.stockListRead ?? false;
        data.create = widget.userRoleModel?.stockListCreate ?? false;
        data.update = widget.userRoleModel?.stockListUpdate ?? false;
        data.delete = widget.userRoleModel?.stockListDelete ?? false;
      } else if (data.title == "Subscription") {
        data.read = widget.userRoleModel?.subscriptionRead ?? false;
        data.create = widget.userRoleModel?.subscriptionCreate ?? false;
        data.update = widget.userRoleModel?.subscriptionUpdate ?? false;
        data.delete = widget.userRoleModel?.subscriptionDelete ?? false;
      } else if (data.title == "User Role") {
        data.read = widget.userRoleModel?.userRoleRead ?? false;
        data.create = widget.userRoleModel?.userRoleCreate ?? false;
        data.update = widget.userRoleModel?.userRoleUpdate ?? false;
        data.delete = widget.userRoleModel?.userRoleDelete ?? false;
      } else if (data.title == "Tax Rate") {
        data.read = widget.userRoleModel?.taxRateRead ?? false;
        data.create = widget.userRoleModel?.taxRateCreate ?? false;
        data.update = widget.userRoleModel?.taxRateUpdate ?? false;
        data.delete = widget.userRoleModel?.taxRateDelete ?? false;
      } else if (data.title == "HRM") {
        data.read = widget.userRoleModel?.hrmRead ?? false;
        data.create = widget.userRoleModel?.hrmCreate ?? false;
        data.update = widget.userRoleModel?.hrmUpdate ?? false;
        data.delete = widget.userRoleModel?.hrmDelete ?? false;
      }
    }
  }

  void _selectAllTabs(bool? value) {
    setState(() {
      isTapped = value ?? false;
      for (var element in permissions) {
        element.read = value!;
        element.create = value;
        element.update = value;
        element.delete = value;
      }
    });
  }

  @override
  Widget build(BuildContext context) {
    final theme = Theme.of(context);
    return SafeArea(
      child: Consumer(
        builder: (context, ref, child) {
          final employeeData = ref.watch(employeeProvider);
          return employeeData.when(
            data: (employees) => _buildMainContent(context, theme, ref, employees),
            error: (e, stack) => Center(child: Text('Error: $e')),
            loading: () => const Center(child: CircularProgressIndicator()),
          );
        },
      ),
    );
  }

  Widget _buildMainContent(
      BuildContext context, ThemeData theme, WidgetRef ref, List<EmployeeModel> employees) {
    return Scaffold(
      backgroundColor: Colors.grey[100],
      body: SingleChildScrollView(
        padding: const EdgeInsets.all(16),
        child: Form(
          key: _formKey,
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Container(
                decoration: BoxDecoration(
                  borderRadius: BorderRadius.circular(20.0),
                  color: Colors.white,
                ),
                child: Column(
                  children: [
                    Padding(
                      padding: const EdgeInsets.all(10.0),
                      child: Row(
                        mainAxisAlignment: MainAxisAlignment.spaceBetween,
                        children: [
                          Flexible(
                            child: Text(
                              'Permission',
                              style: theme.textTheme.titleLarge
                                  ?.copyWith(fontWeight: FontWeight.w600),
                            ),
                          ),
                        ],
                      ),
                    ),
                    const Divider(
                      thickness: 1.0,
                      color: kNeutral300,
                      height: 1,
                    ),
                    Padding(
                      padding: const EdgeInsets.all(10.0),
                      child: ResponsiveGridRow(children: [
                        ResponsiveGridCol(
                            xs: 12,
                            md: 4,
                            lg: 4,
                            child: Padding(
                              padding: const EdgeInsets.all(10.0),
                              child: DropdownButtonFormField<EmployeeModel>(
                                hint: const Text('Select an employee'),
                                decoration: const InputDecoration(
                                  labelText: 'Employee',
                                  hintText: 'Select an employee',
                                ),
                                isExpanded: true,
                                value: selectedEmployee,
                                onChanged: (EmployeeModel? value) {
                                  ref.read(selectedEmployeeProvider.notifier).state = value;
                                  setState(() {
                                    selectedEmployee = value;
                                    if (value != null) {
                                      loginUserController.text = value.email;
                                    } else {
                                      loginUserController.text = '';
                                    }
                                  });
                                },
                                items: employees.map((employee) {
                                  return DropdownMenuItem<EmployeeModel>(
                                    value: employee,
                                    child: Text(employee.name),
                                  );
                                }).toList(),
                              ),
                            )),
                        ResponsiveGridCol(
                            xs: 12,
                            md: 4,
                            lg: 4,
                            child: Padding(
                              padding: const EdgeInsets.all(10.0),
                              child: TextFormField(
                                controller: loginUserController,
                                readOnly: widget.userRoleModel != null,
                                keyboardType: TextInputType.emailAddress,
                                decoration: const InputDecoration(
                                  labelText: 'Login Email',
                                  hintText: 'user@example.com',
                                ),
                                validator: (value) {
                                  if (value == null || value.isEmpty) {
                                    return 'Please enter an email';
                                  }
                                  return null;
                                },
                              ),
                            )),
                        ResponsiveGridCol(
                            xs: 12,
                            md: 4,
                            lg: 4,
                            child: Padding(
                              padding: const EdgeInsets.all(10.0),
                              child: TextFormField(
                                controller: passwordController,
                                obscureText: hidePassword,
                                readOnly: widget.userRoleModel != null,
                                decoration: InputDecoration(
                                  labelText: 'Password',
                                  hintText: '********',
                                  suffixIcon: IconButton(
                                    onPressed: () {
                                      setState(() {
                                        hidePassword = !hidePassword;
                                      });
                                    },
                                    icon: Icon(
                                      hidePassword ? FeatherIcons.eyeOff : FeatherIcons.eye,
                                      color: kGreyTextColor,
                                    ),
                                  ),
                                ),
                                validator: (value) {
                                  if (widget.userRoleModel == null &&
                                      (value == null || value.isEmpty)) {
                                    return 'Please enter a password';
                                  }
                                  return null;
                                },
                              ),
                            ))
                      ]),
                    ),
                    _buildPermissionTable(theme),
                    _buildActionButtons(context, ref),
                  ],
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }

  Widget _buildPermissionTable(ThemeData theme) {
    return Scrollbar(
      thickness: 8.0,
      thumbVisibility: true,
      controller: _horizontalScroll,
      radius: const Radius.circular(5),
      child: LayoutBuilder(
        builder: (BuildContext context, BoxConstraints constraints) {
          final kWidth = constraints.maxWidth;
          return SingleChildScrollView(
            controller: _horizontalScroll,
            scrollDirection: Axis.horizontal,
            child: ConstrainedBox(
              constraints: BoxConstraints(
                minWidth: kWidth,
                minHeight: MediaQuery.of(context).size.height - 373,
              ),
              child: Theme(
                data: ThemeData(
                  dividerColor: kNeutral300,
                  textTheme: theme.textTheme,
                ),
                child: DataTable(
                  border: TableBorder.symmetric(inside: BorderSide(color: kNeutral300)),
                  dataRowColor: const WidgetStatePropertyAll(Colors.white),
                  headingRowColor: WidgetStateProperty.all(kGreyTextColor100),
                  showBottomBorder: true,
                  dividerThickness: 1.0,
                  headingTextStyle: theme.textTheme.titleMedium,
                  dataTextStyle: theme.textTheme.bodyLarge,
                  columns: [
                    DataColumn(label: Text('SL')),
                    const DataColumn(
                        // columnWidth: FixedColumnWidth(),
                        label: Text('Features')),
                    DataColumn(
                      label: Row(
                        children: [
                          Theme(
                            data: Theme.of(context).copyWith(
                              checkboxTheme:
                                  const CheckboxThemeData(side: BorderSide(color: kNeutral500)),
                            ),
                            child: Checkbox(
                              value: isTapped ?? false,
                              onChanged: _selectAllTabs,
                            ),
                          ),
                          const Text('Select All')
                        ],
                      ),
                    ),
                  ],
                  rows: List.generate(
                    permissions.length,
                    (index) {
                      return DataRow(cells: [
                        DataCell(Text((index + 1).toString())),
                        DataCell(Text(permissions[index].title)),
                        DataCell(Row(
                          mainAxisSize: MainAxisSize.min,
                          children: [
                            _buildPermissionCheckbox(
                              value: permissions[index].read,
                              label: 'Read',
                              onChanged: (value) =>
                                  setState(() => permissions[index].read = value ?? false),
                            ),
                            if (!['Dashboard', 'All Reports', 'Profit/ Loss', 'Subscription']
                                .contains(permissions[index].title)) ...[
                              const SizedBox(width: 16),
                              _buildPermissionCheckbox(
                                value: permissions[index].create,
                                label: 'Create',
                                onChanged: (value) =>
                                    setState(() => permissions[index].create = value ?? false),
                              ),
                              const SizedBox(width: 16),
                              _buildPermissionCheckbox(
                                value: permissions[index].update,
                                label: 'Update',
                                onChanged: (value) =>
                                    setState(() => permissions[index].update = value ?? false),
                              ),
                              const SizedBox(width: 16),
                              _buildPermissionCheckbox(
                                value: permissions[index].delete,
                                label: 'Delete',
                                onChanged: (value) =>
                                    setState(() => permissions[index].delete = value ?? false),
                              ),
                            ],
                          ],
                        )),
                      ]);
                    },
                  ),
                ),
              ),
            ),
          );
        },
      ),
    );
  }

  Widget _buildPermissionCheckbox({
    required bool? value,
    required String label,
    required ValueChanged<bool?> onChanged,
  }) {
    return Row(
      children: [
        Theme(
          data: Theme.of(context).copyWith(
            checkboxTheme: const CheckboxThemeData(side: BorderSide(color: kNeutral500)),
          ),
          child: Checkbox(
            value: value ?? false,
            onChanged: onChanged,
          ),
        ),
        Text(label),
      ],
    );
  }

  Widget _buildActionButtons(BuildContext context, WidgetRef ref) {
    return Padding(
      padding: const EdgeInsets.all(20.0),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          OutlinedButton(
            style: OutlinedButton.styleFrom(minimumSize: Size(134, 48)),
            onPressed: () => setState(() {
              titleController.clear();
              _selectAllTabs(false);
            }),
            child: const Text('Reset'),
          ),
          const SizedBox(width: 18),
          ElevatedButton(
            style: ElevatedButton.styleFrom(minimumSize: Size(134, 48)),
            onPressed: () => _saveUserRole(context, ref),
            child: Text(widget.userRoleModel != null ? "Update" : 'Save'),
          ),
        ],
      ),
    );
  }

  Future<void> _saveUserRole(BuildContext context, WidgetRef ref) async {
    if (!_formKey.currentState!.validate()) return;

    if ((loginUserController.text.isEmpty || passwordController.text.trim().isEmpty) &&
        widget.userRoleModel == null) {
      EasyLoading.showError('Please fill all required fields');
      return;
    }

    // Create permission model
    final userRoleModel = _createUserRoleModel();

    // Check if any permission is granted
    final hasAnyPermission = permissions
        .any((element) => element.read || element.create || element.update || element.delete);
    if (!hasAnyPermission) {
      EasyLoading.showError('You must grant at least one permission');
      return;
    }

    try {
      EasyLoading.show(
          status: widget.userRoleModel != null ? "Updating..." : 'Saving...', dismissOnTap: false);

      if (widget.userRoleModel != null) {
        userRoleModel.id = widget.userRoleModel!.id;
        userRoleModel.userEmail = widget.userRoleModel!.userEmail;
        userRoleModel.databaseId = widget.userRoleModel!.databaseId;
        await _updateExistingUserRole(userRoleModel);
      } else {
        if (widget.users != null && widget.users!.isNotEmpty) {
          final emailExists =
              widget.users!.any((user) => user.userEmail == loginUserController.text.trim());
          if (emailExists) {
            EasyLoading.showError('This email is already assigned to another role');
            return;
          }
        }
        await _createNewUserRole(context, ref, userRoleModel);
        createUser();
      }

      ref.refresh(userRoleProvider);
      EasyLoading.showSuccess(
          widget.userRoleModel != null ? 'Successfully updated' : 'Successfully added');
      if (context.mounted) GoRouter.of(context).go('/user-role');
      // context.go('/add-user-role');
    } catch (e) {
      EasyLoading.dismiss();
      if (context.mounted) {
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(content: Text('Error: ${e.toString()}')),
        );
      }
    }
  }

  UserRoleModel _createUserRoleModel() {
    final userRolePermissionModel = UserRoleModel();

    for (var data in permissions) {
      if (data.title == "Dashboard") {
        print('Dashboard Read: ${data.read}');
        userRolePermissionModel.dashboardRead = data.read;
      } else if (data.title == "Pos Sale") {
        print(
            'Pos Sale Read: ${data.read}, Create: ${data.create}, Update: ${data.update}, Delete: ${data.delete}');
        userRolePermissionModel.posSaleRead = data.read;
        userRolePermissionModel.posSaleCreate = data.create;
        userRolePermissionModel.posSaleUpdate = data.update;
        userRolePermissionModel.posSaleDelete = data.delete;
      } else if (data.title == "Inventory Sales") {
        print(
            'Inventory Sales Read: ${data.read}, Create: ${data.create}, Update: ${data.update}, Delete: ${data.delete}');
        userRolePermissionModel.inventorySaleRead = data.read;
        userRolePermissionModel.inventorySaleCreate = data.create;
        userRolePermissionModel.inventorySaleUpdate = data.update;
        userRolePermissionModel.inventorySaleDelete = data.delete;
      } else if (data.title == "Sale List") {
        print(
            'Sale List Read: ${data.read}, Create: ${data.create}, Update: ${data.update}, Delete: ${data.delete}');
        userRolePermissionModel.saleListRead = data.read;
        userRolePermissionModel.saleListCreate = data.create;
        userRolePermissionModel.saleListUpdate = data.update;
        userRolePermissionModel.saleListDelete = data.delete;
      } else if (data.title == "Sale Return") {
        print(
            'Sale Return Read: ${data.read}, Create: ${data.create}, Update: ${data.update}, Delete: ${data.delete}');
        userRolePermissionModel.saleReturnRead = data.read;
        userRolePermissionModel.saleReturnCreate = data.create;
        userRolePermissionModel.saleReturnUpdate = data.update;
        userRolePermissionModel.saleReturnDelete = data.delete;
      } else if (data.title == "Purchase") {
        print(
            'Purchase Read: ${data.read}, Create: ${data.create}, Update: ${data.update}, Delete: ${data.delete}');
        userRolePermissionModel.purchaseRead = data.read;
        userRolePermissionModel.purchaseCreate = data.create;
        userRolePermissionModel.purchaseUpdate = data.update;
        userRolePermissionModel.purchaseDelete = data.delete;
      } else if (data.title == "Purchase List") {
        print(
            'Purchase List Read: ${data.read}, Create: ${data.create}, Update: ${data.update}, Delete: ${data.delete}');
        userRolePermissionModel.purchaseRead = data.read;
        userRolePermissionModel.purchaseCreate = data.create;
        userRolePermissionModel.purchaseUpdate = data.update;
        userRolePermissionModel.purchaseDelete = data.delete;
      } else if (data.title == "Purchase Return") {
        print(
            'Purchase Return Read: ${data.read}, Create: ${data.create}, Update: ${data.update}, Delete: ${data.delete}');
        userRolePermissionModel.purchaseReturnRead = data.read;
        userRolePermissionModel.purchaseReturnCreate = data.create;
        userRolePermissionModel.purchaseReturnUpdate = data.update;
        userRolePermissionModel.purchaseReturnDelete = data.delete;
      } else if (data.title == "Quotation List") {
        print(
            'Quotation List Read: ${data.read}, Create: ${data.create}, Update: ${data.update}, Delete: ${data.delete}');
        userRolePermissionModel.quotationListRead = data.read;
        userRolePermissionModel.quotationListCreate = data.create;
        userRolePermissionModel.quotationListUpdate = data.update;
        userRolePermissionModel.quotationListDelete = data.delete;
      } else if (data.title == "Product") {
        print(
            'Product Read: ${data.read}, Create: ${data.create}, Update: ${data.update}, Delete: ${data.delete}');
        userRolePermissionModel.productRead = data.read;
        userRolePermissionModel.productCreate = data.create;
        userRolePermissionModel.productUpdate = data.update;
        userRolePermissionModel.productDelete = data.delete;
      } else if (data.title == "Low Stock") {
        print(
            'Low Stock Read: ${data.read}, Create: ${data.create}, Update: ${data.update}, Delete: ${data.delete}');
        userRolePermissionModel.lowStockRead = data.read;
        userRolePermissionModel.lowStockCreate = data.create;
        userRolePermissionModel.lowStockUpdate = data.update;
        userRolePermissionModel.lowStockDelete = data.delete;
      } else if (data.title == "Expired") {
        print(
            'Expired Read: ${data.read}, Create: ${data.create}, Update: ${data.update}, Delete: ${data.delete}');
        userRolePermissionModel.expiredRead = data.read;
        userRolePermissionModel.expiredCreate = data.create;
        userRolePermissionModel.expiredUpdate = data.update;
        userRolePermissionModel.expiredDelete = data.delete;
      } else if (data.title == "Categories") {
        print(
            'Categories Read: ${data.read}, Create: ${data.create}, Update: ${data.update}, Delete: ${data.delete}');
        userRolePermissionModel.categoriesRead = data.read;
        userRolePermissionModel.categoriesCreate = data.create;
        userRolePermissionModel.categoriesUpdate = data.update;
        userRolePermissionModel.categoriesDelete = data.delete;
      } else if (data.title == "Brand") {
        print(
            'Brand Read: ${data.read}, Create: ${data.create}, Update: ${data.update}, Delete: ${data.delete}');
        userRolePermissionModel.brandRead = data.read;
        userRolePermissionModel.brandCreate = data.create;
        userRolePermissionModel.brandUpdate = data.update;
        userRolePermissionModel.brandDelete = data.delete;
      } else if (data.title == "Unit") {
        print(
            'Unit Read: ${data.read}, Create: ${data.create}, Update: ${data.update}, Delete: ${data.delete}');
        userRolePermissionModel.unitRead = data.read;
        userRolePermissionModel.unitCreate = data.create;
        userRolePermissionModel.unitUpdate = data.update;
        userRolePermissionModel.unitDelete = data.delete;
      } else if (data.title == "Warehouse") {
        print(
            'Warehouse Read: ${data.read}, Create: ${data.create}, Update: ${data.update}, Delete: ${data.delete}');
        userRolePermissionModel.wareHouseRead = data.read;
        userRolePermissionModel.wareHouseCreate = data.create;
        userRolePermissionModel.wareHouseUpdate = data.update;
        userRolePermissionModel.wareHouseDelete = data.delete;
      } else if (data.title == "Supplier List") {
        print(
            'Supplier List Read: ${data.read}, Create: ${data.create}, Update: ${data.update}, Delete: ${data.delete}');
        userRolePermissionModel.supplierListRead = data.read;
        userRolePermissionModel.supplierListCreate = data.create;
        userRolePermissionModel.supplierListUpdate = data.update;
        userRolePermissionModel.supplierListDelete = data.delete;
      } else if (data.title == "Customer List") {
        print(
            'Customer List Read: ${data.read}, Create: ${data.create}, Update: ${data.update}, Delete: ${data.delete}');
        userRolePermissionModel.customerListRead = data.read;
        userRolePermissionModel.customerListCreate = data.create;
        userRolePermissionModel.customerListUpdate = data.update;
        userRolePermissionModel.customerListDelete = data.delete;
      } else if (data.title == "Due List") {
        print(
            'Due List Read: ${data.read}, Create: ${data.create}, Update: ${data.update}, Delete: ${data.delete}');
        userRolePermissionModel.dueListRead = data.read;
        userRolePermissionModel.dueListCreate = data.create;
        userRolePermissionModel.dueListUpdate = data.update;
        userRolePermissionModel.dueListDelete = data.delete;
      } else if (data.title == "Ledger") {
        print(
            'Ledger Read: ${data.read}, Create: ${data.create}, Update: ${data.update}, Delete: ${data.delete}');
        userRolePermissionModel.ledgerRead = data.read;
        userRolePermissionModel.ledgerCreate = data.create;
        userRolePermissionModel.ledgerUpdate = data.update;
        userRolePermissionModel.ledgerDelete = data.delete;
      } else if (data.title == "Profit/ Loss") {
        print(
            'Profit/Loss Read: ${data.read}, Create: ${data.create}, Update: ${data.update}, Delete: ${data.delete}');
        userRolePermissionModel.lossProfitRead = data.read;
        userRolePermissionModel.lossProfitCreate = data.create;
        userRolePermissionModel.lossProfitUpdate = data.update;
        userRolePermissionModel.lossProfitDelete = data.delete;
      } else if (data.title == "Payment Type") {
        print(
            'Payment Type Read: ${data.read}, Create: ${data.create}, Update: ${data.update}, Delete: ${data.delete}');
        userRolePermissionModel.paymentTypeRead = data.read;
        userRolePermissionModel.paymentTypeCreate = data.create;
        userRolePermissionModel.paymentTypeUpdate = data.update;
        userRolePermissionModel.paymentTypeDelete = data.delete;
      } else if (data.title == "Expense") {
        print(
            'Expense Read: ${data.read}, Create: ${data.create}, Update: ${data.update}, Delete: ${data.delete}');
        userRolePermissionModel.expenseRead = data.read;
        userRolePermissionModel.expenseCreate = data.create;
        userRolePermissionModel.expenseUpdate = data.update;
        userRolePermissionModel.expenseDelete = data.delete;
      } else if (data.title == "Expense Category") {
        print(
            'Expense Category Read: ${data.read}, Create: ${data.create}, Update: ${data.update}, Delete: ${data.delete}');
        userRolePermissionModel.expenseCategoryRead = data.read;
        userRolePermissionModel.expenseCategoryCreate = data.create;
        userRolePermissionModel.expenseCategoryUpdate = data.update;
        userRolePermissionModel.expenseCategoryDelete = data.delete;
      } else if (data.title == "Income") {
        print(
            'Income Read: ${data.read}, Create: ${data.create}, Update: ${data.update}, Delete: ${data.delete}');
        userRolePermissionModel.incomeRead = data.read;
        userRolePermissionModel.incomeCreate = data.create;
        userRolePermissionModel.incomeUpdate = data.update;
        userRolePermissionModel.incomeDelete = data.delete;
      } else if (data.title == "Income Category") {
        print(
            'Income Category Read: ${data.read}, Create: ${data.create}, Update: ${data.update}, Delete: ${data.delete}');
        userRolePermissionModel.incomeCategoryRead = data.read;
        userRolePermissionModel.incomeCategoryCreate = data.create;
        userRolePermissionModel.incomeCategoryUpdate = data.update;
        userRolePermissionModel.incomeCategoryDelete = data.delete;
      } else if (data.title == "Transaction") {
        print(
            'Transaction Read: ${data.read}, Create: ${data.create}, Update: ${data.update}, Delete: ${data.delete}');
        userRolePermissionModel.transactionRead = data.read;
        userRolePermissionModel.transactionCreate = data.create;
        userRolePermissionModel.transactionUpdate = data.update;
        userRolePermissionModel.transactionDelete = data.delete;
      } else if (data.title == "All Reports") {
        print(
            'All Reports Read: ${data.read}, Create: ${data.create}, Update: ${data.update}, Delete: ${data.delete}');
        userRolePermissionModel.allReportsRead = data.read;
        userRolePermissionModel.allReportsCreate = data.create;
        userRolePermissionModel.allReportsUpdate = data.update;
        userRolePermissionModel.allReportsDelete = data.delete;
      } else if (data.title == "WhatsApp Marketing") {
        print(
            'WhatsApp Marketing Read: ${data.read}, Create: ${data.create}, Update: ${data.update}, Delete: ${data.delete}');
        userRolePermissionModel.whatsAppMarketingRead = data.read;
        userRolePermissionModel.whatsAppMarketingCreate = data.create;
        userRolePermissionModel.whatsAppMarketingUpdate = data.update;
        userRolePermissionModel.whatsAppMarketingDelete = data.delete;
      } else if (data.title == "Stock List") {
        print(
            'Stock List Read: ${data.read}, Create: ${data.create}, Update: ${data.update}, Delete: ${data.delete}');
        userRolePermissionModel.stockListRead = data.read;
        userRolePermissionModel.stockListCreate = data.create;
        userRolePermissionModel.stockListUpdate = data.update;
        userRolePermissionModel.stockListDelete = data.delete;
      } else if (data.title == "Subscription") {
        print(
            'Subscription Read: ${data.read}, Create: ${data.create}, Update: ${data.update}, Delete: ${data.delete}');
        userRolePermissionModel.subscriptionRead = data.read;
        userRolePermissionModel.subscriptionCreate = data.create;
        userRolePermissionModel.subscriptionUpdate = data.update;
        userRolePermissionModel.subscriptionDelete = data.delete;
      } else if (data.title == "User Role") {
        print(
            'User Role Read: ${data.read}, Create: ${data.create}, Update: ${data.update}, Delete: ${data.delete}');
        userRolePermissionModel.userRoleRead = data.read;
        userRolePermissionModel.userRoleCreate = data.create;
        userRolePermissionModel.userRoleUpdate = data.update;
        userRolePermissionModel.userRoleDelete = data.delete;
      } else if (data.title == "Tax Rate") {
        print(
            'Tax Rate Read: ${data.read}, Create: ${data.create}, Update: ${data.update}, Delete: ${data.delete}');
        userRolePermissionModel.taxRateRead = data.read;
        userRolePermissionModel.taxRateCreate = data.create;
        userRolePermissionModel.taxRateUpdate = data.update;
        userRolePermissionModel.taxRateDelete = data.delete;
      } else if (data.title == "HRM") {
        print(
            'HRM Read: ${data.read}, Create: ${data.create}, Update: ${data.update}, Delete: ${data.delete}');
        userRolePermissionModel.hrmRead = data.read;
        userRolePermissionModel.hrmCreate = data.create;
        userRolePermissionModel.hrmUpdate = data.update;
        userRolePermissionModel.hrmDelete = data.delete;
      } else {
        print('Unknown Feature: ${data.title}, Read: ${data.read}');
        userRolePermissionModel.dashboardRead = data.read;
      }
    }
    print('User Role Model: ${userRolePermissionModel.toJson()}');
    return userRolePermissionModel;
  }

  Future<void> _updateExistingUserRole(UserRoleModel userRoleModel) async {
    try {
      EasyLoading.show(status: 'Updating...', dismissOnTap: false);

      final currentUser = FirebaseAuth.instance.currentUser;
      if (currentUser == null || currentUser.uid.isEmpty) {
        throw Exception('User not authenticated');
      }
      final userPath = "${currentUser.uid}/User Role/${userRoleModel.id}";
      final adminPath = "Admin Panel/User Role/${userRoleModel.id}";
      await FirebaseDatabase.instance.ref(userPath).update(userRoleModel.toJson());
      await FirebaseDatabase.instance.ref(adminPath).update(userRoleModel.toJson());

      EasyLoading.showSuccess('Successfully updated');
    } catch (e) {
      EasyLoading.dismiss();
      rethrow;
    }
  }

  Future<void> _createNewUserRole(
      BuildContext context, WidgetRef ref, UserRoleModel userRoleModel) async {
    try {
      final currentUser = FirebaseAuth.instance.currentUser?.uid;
      DatabaseReference dataRef = FirebaseDatabase.instance.ref("$currentUser/User Role");
      DatabaseReference adminDataRef = FirebaseDatabase.instance.ref("Admin Panel/User Role");
      String pushKey = dataRef.push().key ?? '';
      userRoleModel.id = pushKey;
      userRoleModel.userEmail = loginUserController.text.trim();
      userRoleModel.databaseId = currentUser ?? '';
      await Future.wait([
        dataRef.child(userRoleModel.id ?? "").update(userRoleModel.toJson()),
        adminDataRef.child(userRoleModel.id ?? "").update(userRoleModel.toJson()),
        //FirebaseAuth.instance.createUserWithEmailAndPassword(email: loginUserController.text.trim(), password: passwordController.text.trim()),
      ]);
      ref.refresh(userRoleProvider);

      EasyLoading.showSuccess(lang.S.of(context).successfullyUpdated,
          duration: const Duration(milliseconds: 500));
    } on FirebaseAuthException catch (e) {
      throw Exception('Registration failed: ${e.message}');
    }
  }

  Future<void> createUser() async {
    try {
      await FirebaseAuth.instance.createUserWithEmailAndPassword(
        email: loginUserController.text.trim(),
        password: passwordController.text.trim(),
      );
      await FirebaseAuth.instance.signOut();
      final prefs = await SharedPreferences.getInstance();
      String mainUserEmail = prefs.getString('userEmail') ?? '';
      String mainUserPassword = prefs.getString('userPassword') ?? '';
      await FirebaseAuth.instance.signInWithEmailAndPassword(
        email: mainUserEmail,
        password: mainUserPassword,
      );
      EasyLoading.showSuccess('User created successfully');
    } on FirebaseAuthException catch (e) {
      if (e.code == 'email-already-in-use') {
        EasyLoading.showError('The email is already in use by another account.');
      } else {
        EasyLoading.showError('Failed to create user: ${e.message}');
      }
    } catch (e) {
      EasyLoading.showError('An unexpected error occurred: $e');
    }
  }
}
