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_riverpod/flutter_riverpod.dart';
import 'package:google_fonts/google_fonts.dart';
import 'package:mobile_pos/GlobalComponents/button_global.dart';
import 'package:mobile_pos/Screens/Authentication/login_form.dart';
import 'package:mobile_pos/constant.dart';
import 'package:mobile_pos/generated/l10n.dart' as lang;
import 'package:mobile_pos/model/user_role_model.dart';
import 'package:nb_utils/nb_utils.dart';

import '../../Provider/user_role_provider.dart';
import '../HRM/employees/model/employee_model.dart';
import '../HRM/employees/provider/designation_provider.dart';

class AddUserRole extends StatefulWidget {
  AddUserRole({super.key, this.userRoleModel, this.users});

  UserRoleModel? userRoleModel;
  List<UserRoleModel>? users;

  @override
  // ignore: library_private_types_in_public_api
  _AddUserRoleState createState() => _AddUserRoleState();
}

class _AddUserRoleState extends State<AddUserRole> {
  final GlobalKey<FormState> _formKey = GlobalKey<FormState>();
  final ScrollController _horizontalScroll = ScrollController();
  final TextEditingController loginUserController = TextEditingController();
  final TextEditingController passwordController = TextEditingController();
  final TextEditingController titleController = TextEditingController();

  EmployeeModel? selectedEmployee;
  final selectedEmployeeProvider = StateProvider<EmployeeModel?>((ref) => null);

  bool? isTapped;
  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) {
    return Consumer(builder: (context, ref, __) {
      final employeeData = ref.watch(employeeProvider);
      return Scaffold(
        backgroundColor: Colors.white,
        appBar: AppBar(
          backgroundColor: Colors.white,
          title: Text(
            lang.S.of(context).addUserRole,
            style: GoogleFonts.poppins(
              color: Colors.black,
            ),
          ),
          centerTitle: true,
          iconTheme: const IconThemeData(color: Colors.black),
          elevation: 0.0,
        ),
        body: employeeData.when(
          data: (employees) {
            return SingleChildScrollView(
              child: Padding(
                padding: const EdgeInsets.all(10.0),
                child: Column(
                  children: [
                    Padding(
                      padding: const EdgeInsets.all(10.0),
                      child: Container(
                        decoration: BoxDecoration(
                          border: Border.all(width: 0.5, color: kGreyTextColor),
                          borderRadius: const BorderRadius.all(Radius.circular(10)),
                        ),
                        child: Column(
                          children: [
                            ListTile(
                              title: Text("Type"),
                              trailing: Row(
                                mainAxisSize: MainAxisSize.min,
                                children: [
                                  Text("View",
                                      style: TextStyle(color: textPrimaryColor, fontSize: 16)),
                                  SizedBox(width: 10),
                                  Text("Create",
                                      style: TextStyle(color: textPrimaryColor, fontSize: 16)),
                                  SizedBox(width: 10),
                                  Text("Edit",
                                      style: TextStyle(color: textPrimaryColor, fontSize: 16)),
                                  SizedBox(width: 10),
                                  Text("Delete",
                                      style: TextStyle(color: textPrimaryColor, fontSize: 16)),
                                ],
                              ),
                            ),
                            Divider(),
                            //Add a select all button
                            ListTile(
                              title: Text("Select All",
                                  style: TextStyle(fontWeight: FontWeight.bold, fontSize: 16)),
                              trailing: Checkbox(
                                value: isTapped ?? false,
                                onChanged: _selectAllTabs,
                              ),
                            ),
                            ListView.builder(
                              shrinkWrap: true,
                              physics: const NeverScrollableScrollPhysics(),
                              itemCount: permissions.length,
                              itemBuilder: (context, index) {
                                return ListTile(
                                  title: Text(permissions[index].title),
                                  trailing: Row(
                                    mainAxisSize: MainAxisSize.min,
                                    children: [
                                      Checkbox(
                                        value: permissions[index].read,
                                        onChanged: (bool? value) {
                                          setState(() {
                                            permissions[index].read = value ?? false;
                                          });
                                        },
                                      ),
                                      Checkbox(
                                        value: permissions[index].create,
                                        onChanged: (bool? value) {
                                          setState(() {
                                            permissions[index].create = value ?? false;
                                          });
                                        },
                                      ),
                                      Checkbox(
                                        value: permissions[index].update,
                                        onChanged: (bool? value) {
                                          setState(() {
                                            permissions[index].update = value ?? false;
                                          });
                                        },
                                      ),
                                      Checkbox(
                                        value: permissions[index].delete,
                                        onChanged: (bool? value) {
                                          setState(() {
                                            permissions[index].delete = value ?? false;
                                          });
                                        },
                                      ),
                                    ],
                                  ),
                                );
                              },
                            ),
                          ],
                        ),
                      ),
                    ),

                    ///___________Text_fields_____________________________________________
                    if (widget.userRoleModel == null) ...[
                      Padding(
                        padding: const EdgeInsets.all(10.0),
                        child: Form(
                          key: _formKey,
                          child: Column(
                            children: [
                              DropdownButtonFormField<EmployeeModel>(
                                hint: const Text('Select an employee'),
                                decoration: kInputDecoration.copyWith(
                                  labelText: "Employee",
                                  // labelStyle: kTextStyle.copyWith(color: kTitleColor),
                                  hintText: 'Select an employee',
                                  // hintStyle: kTextStyle.copyWith(color: kLitGreyColor),
                                  contentPadding: const EdgeInsets.all(10.0),
                                  enabledBorder: const OutlineInputBorder(
                                    borderRadius: BorderRadius.all(
                                      Radius.circular(4.0),
                                    ),
                                    borderSide: BorderSide(color: kBorderColorTextField, width: 1),
                                  ),
                                  errorBorder: const OutlineInputBorder(
                                      borderSide: BorderSide(color: Colors.red)),
                                  focusedBorder: const OutlineInputBorder(
                                    borderRadius: BorderRadius.all(Radius.circular(4.0)),
                                    borderSide: BorderSide(color: kBorderColorTextField, width: 2),
                                  ),
                                ),
                                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(),
                              ),
                              const SizedBox(height: 20.0),

                              ///__________email_________________________________________________________
                              AppTextField(
                                validator: (value) {
                                  if (value == null || value.isEmpty) {
                                    // return 'Email can\'n be empty';
                                    return lang.S.of(context).emailCanNotBeEmpty;
                                  } else if (!value.contains('@')) {
                                    //return 'Please enter a valid email';
                                    return lang.S.of(context).pleaseEnterAValidEmail;
                                  }
                                  return null;
                                },
                                showCursor: true,
                                controller: loginUserController,
                                // cursorColor: kTitleColor,
                                decoration: kInputDecoration.copyWith(
                                  labelText: lang.S.of(context).email,
                                  // labelStyle: kTextStyle.copyWith(color: kTitleColor),
                                  hintText: lang.S.of(context).enterYourEmailAddress,
                                  // hintStyle: kTextStyle.copyWith(color: kLitGreyColor),
                                  contentPadding: const EdgeInsets.all(10.0),
                                  enabledBorder: const OutlineInputBorder(
                                    borderRadius: BorderRadius.all(
                                      Radius.circular(4.0),
                                    ),
                                    borderSide: BorderSide(color: kBorderColorTextField, width: 1),
                                  ),
                                  errorBorder: const OutlineInputBorder(
                                      borderSide: BorderSide(color: Colors.red)),
                                  focusedBorder: const OutlineInputBorder(
                                    borderRadius: BorderRadius.all(Radius.circular(4.0)),
                                    borderSide: BorderSide(color: kBorderColorTextField, width: 2),
                                  ),
                                ),
                                textFieldType: TextFieldType.EMAIL,
                              ),
                              const SizedBox(height: 20.0),

                              ///______password___________________________________________________________
                              AppTextField(
                                validator: (value) {
                                  if (value == null || value.isEmpty) {
                                    //return 'Password can\'t be empty';
                                    return lang.S.of(context).passwordCanNotBeEmpty;
                                  } else if (value.length < 4) {
                                    //return 'Please enter a bigger password';
                                    return lang.S.of(context).pleaseEnterABiggerPassword;
                                  }
                                  return null;
                                },
                                controller: passwordController,
                                showCursor: true,
                                // cursorColor: kTitleColor,
                                decoration: kInputDecoration.copyWith(
                                  labelText: lang.S.of(context).password,
                                  floatingLabelAlignment: FloatingLabelAlignment.start,
                                  // labelStyle: kTextStyle.copyWith(color: kTitleColor),
                                  hintText: lang.S.of(context).enterYourPassword,
                                  // hintStyle: kTextStyle.copyWith(color: kLitGreyColor),
                                  contentPadding: const EdgeInsets.all(10.0),
                                  enabledBorder: const OutlineInputBorder(
                                    borderRadius: BorderRadius.all(
                                      Radius.circular(4.0),
                                    ),
                                    borderSide: BorderSide(color: kBorderColorTextField, width: 1),
                                  ),
                                  errorBorder: const OutlineInputBorder(
                                      borderSide: BorderSide(color: Colors.red)),
                                  focusedBorder: const OutlineInputBorder(
                                    borderRadius: BorderRadius.all(Radius.circular(4.0)),
                                    borderSide: BorderSide(color: kBorderColorTextField, width: 2),
                                  ),
                                ),
                                textFieldType: TextFieldType.PASSWORD,
                              ),
                              //
                              // ///__________Title_________________________________________________________
                              // const SizedBox(height: 20.0),
                              // AppTextField(
                              //   validator: (value) {
                              //     if (value == null || value.isEmpty) {
                              //       // return 'User title can\'n be empty';
                              //       return lang.S.of(context).userTitleCanNotBeEmpty;
                              //     }
                              //     return null;
                              //   },
                              //   showCursor: true,
                              //   controller: titleController,
                              //   decoration: kInputDecoration.copyWith(
                              //     labelText: lang.S.of(context).userTitle,
                              //     hintText: lang.S.of(context).enterUserTitle,
                              //     contentPadding: const EdgeInsets.all(10.0),
                              //     errorBorder: const OutlineInputBorder(borderSide: BorderSide(color: Colors.red)),
                              //     enabledBorder: const OutlineInputBorder(
                              //       borderRadius: BorderRadius.all(
                              //         Radius.circular(4.0),
                              //       ),
                              //       borderSide: BorderSide(color: kBorderColorTextField, width: 1),
                              //     ),
                              //     focusedBorder: const OutlineInputBorder(
                              //       borderRadius: BorderRadius.all(Radius.circular(4.0)),
                              //       borderSide: BorderSide(color: kBorderColorTextField, width: 2),
                              //     ),
                              //   ),
                              //   textFieldType: TextFieldType.EMAIL,
                              // ),
                              const SizedBox(height: 20.0),
                            ],
                          ),
                        ),
                      ),
                    ]
                  ],
                ),
              ),
            );
          },
          error: (e, stack) => Center(child: Text('Error: $e')),
          loading: () => const Center(child: CircularProgressIndicator()),
        ),
        bottomNavigationBar: Container(
          height: 60,
          margin: const EdgeInsets.all(10.0),
          child: ButtonGlobalWithoutIcon(
              buttonSize: 48,
              buttonTextSize: 18,
              buttontext: widget.userRoleModel != null
                  ? lang.S.of(context).update
                  : lang.S.of(context).create,
              buttonDecoration: kButtonDecoration.copyWith(color: kMainColor),
              onPressed: (() async {
                _saveUserRole(context, ref);
              }),
              buttonTextColor: Colors.white),
        ),
      );
    });
  }

  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> _saveUserRole(BuildContext context, WidgetRef ref) async {
    if (widget.userRoleModel == null && !_formKey.currentState!.validate()) return;

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

    print("create user role");
    // Create permission model
    final userRoleModel = _createUserRoleModel();

    print("user role model created");

    // 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, ref);
      } else {
        if (widget.users != null &&
            widget.users!.any((element) => element.userEmail == loginUserController.text.trim())) {
          EasyLoading.showError('This email is already in use. Please use a different email.');
          return;
        }
        print("create new user role");
        await _createNewUserRole(context, ref, userRoleModel);
      }
      // context.go('/add-user-role');
    } catch (e) {
      EasyLoading.dismiss();
      if (context.mounted) {
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(content: Text('Error: ${e.toString()}')),
        );
      }
    }
  }

  Future<void> _updateExistingUserRole(
    UserRoleModel userRoleModel,
    WidgetRef ref,
  ) 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');
      ref.refresh(userRoleProvider);
      Navigator.pop(context);
    } 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));
      signUp(
          context: context,
          email: loginUserController.text,
          password: passwordController.text,
          ref: ref,
          userRoleModel: userRoleModel);
    } on FirebaseAuthException catch (e) {
      throw Exception('Registration failed: ${e.message}');
    }
  }
}

void signUp(
    {required BuildContext context,
    required String email,
    required String password,
    required WidgetRef ref,
    required UserRoleModel userRoleModel}) async {
  if (!isDemo) {
    EasyLoading.show(status: '${lang.S.of(context).registering}....');
    try {
      UserCredential userCredential = await FirebaseAuth.instance
          .createUserWithEmailAndPassword(email: email, password: password);
      // ignore: unnecessary_null_comparison
      if (userCredential != null) {
        EasyLoading.dismiss();
        await FirebaseAuth.instance.signOut();
        // ignore: use_build_context_synchronously
        await showSussesScreenAndLogOut(context: context);
      }
    } on FirebaseAuthException catch (e) {
      EasyLoading.showError(lang.S.of(context).failedWithError);
      if (e.code == 'weak-password') {
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(
            content: Text('${lang.S.of(context).thePasswordProvidedIsTooWeak}.'),
            duration: const Duration(seconds: 3),
          ),
        );
      } else if (e.code == 'email-already-in-use') {
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(
            //content: Text('The account already exists for that email.'),
            content: Text('${lang.S.of(context).theAccountAlreadyExistsForThatEmail}.'),
            duration: Duration(seconds: 3),
          ),
        );
      }
    } catch (e) {
      EasyLoading.showError(lang.S.of(context).failedWithError);
      ScaffoldMessenger.of(context).showSnackBar(
        SnackBar(
          content: Text(e.toString()),
          duration: const Duration(seconds: 3),
        ),
      );
    }
  } else {
    EasyLoading.showError(demoText);
  }
}

Future showSussesScreenAndLogOut({required BuildContext context}) {
  return showDialog(
    barrierDismissible: false,
    context: context,
    builder: (BuildContext context) {
      return WillPopScope(
        onWillPop: () async {
          return false;
        },
        child: Padding(
          padding: const EdgeInsets.all(30.0),
          child: Center(
            child: Container(
              width: double.infinity,
              decoration: const BoxDecoration(
                color: Colors.white,
                borderRadius: BorderRadius.all(Radius.circular(30)),
              ),
              child: Padding(
                padding: const EdgeInsets.all(10.0),
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.center,
                  mainAxisSize: MainAxisSize.min,
                  children: [
                    const SizedBox(height: 20),
                    Text(
                      lang.S.of(context).addSuccessful,
                      style: const TextStyle(fontSize: 22),
                    ),
                    const SizedBox(height: 10),
                    Text(
                      lang.S.of(context).youHaveToReLogin,
                      textAlign: TextAlign.center,
                      style: const TextStyle(
                        fontSize: 18,
                      ),
                    ),
                    const SizedBox(height: 20),
                    ButtonGlobalWithoutIcon(
                        buttontext: lang.S.of(context).ok,
                        buttonDecoration: kButtonDecoration.copyWith(color: Colors.green),
                        onPressed: (() {
                          const LoginForm().launch(context, isNewTask: true);
                          // const SplashScreen().launch(context, isNewTask: true);
                        }),
                        buttonTextColor: Colors.white),
                  ],
                ),
              ),
            ),
          ),
        ),
      );
    },
  );
}
