import 'dart:convert';

import 'package:firebase_database/firebase_database.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:nb_utils/nb_utils.dart';
import 'package:shared_preferences/shared_preferences.dart';

import 'model/user_role_model.dart';

String currency = '\$';
String currencyName = 'United States Dollar';

List<String> items = [
  '\$ (US Dollar)',
  "₹ (Rupee)",
  "€ (Euro)",
  "₽ (Ruble)",
  "£ (UK Pound)",
  '৳ (Taka)',
  "R (Rial)",
  "؋ (Afghani)",
  "Lek (Lek)",
  "د.ج (Algerian Dinar)",
  "Kz (Kwanza)",
  "EC\$ (East Caribbean Dollar)",
  "\$ (Argentine Peso)",
  "֏ (Armenian Dram)",
  "A\$ (Australian Dollar)",
  "₼ (Azerbaijani Manat)",
  "B\$ (Bahamian Dollar)",
  ".د.ب (Bahraini Dinar)",
  "৳ (Bangladeshi Taka)",
  "Bds\$ (Barbadian Dollar)",
  "Br (Belarusian Ruble)",
  "BZ\$ (Belize Dollar)",
  "CFA (West African CFA franc)",
  "FCFA (West African franc)",
  "Nu. (Bhutanese Ngultrum)",
  "Bs. (Bolivian Boliviano)",
  "KM (Bosnia and Herzegovina Convertible Mark)",
  "P (Botswana Pula)",
  "R\$ (Brazilian Real)",
  "B\$ (Brunei Dollar)",
  "лв (Bulgarian Lev)",
  "FBu (Burundian Franc)",
  "Esc (Cape Verdean Escudo)",
  "៛ (Cambodian Riel)",
  "CFA (Central African CFA franc)",
  "CA\$ (Canadian Dollar)",
  "\$ (Chilean Peso)",
  "¥ (Chinese Yuan)",
  "\$ (Colombian Peso)",
  "CF (Comorian Franc)",
  "FC (Congolese Franc)",
  "₡ (Costa Rican Colón)",
  "kn (Croatian Kuna)",
  "CUP (Cuban Peso)",
  "Kč (Czech Koruna)",
  "kr (Danish Krone)",
  "Fdj (Djiboutian Franc)",
  "RD\$ (Dominican Peso)",
  "US\$ (United States Dollar)",
  "\$ (United States Dollar)",
  "E£ (Egyptian Pound)",
  "Nfk (Eritrean Nakfa)",
  "E (Swazi Lilangeni)",
  "Br (Ethiopian Birr)",
  "FJ\$ (Fijian Dollar)",
  "D (Gambian Dalasi)",
  "₾ (Georgian Lari)",
  "GH₵ (Ghanaian Cedi)",
  "Q (Guatemalan Quetzal)",
  "GNF (Guinean Franc)",
  "GY\$ (Guyanese Dollar)",
  "G (Haitian Gourde)",
  "L (Honduran Lempira)",
  "Ft (Hungarian Forint)",
  "kr (Icelandic Króna)",
  "₹ (Indian Rupee)",
  "Rp (Indonesian Rupiah)",
  "﷼ (Iranian Rial)",
  "ع.د (Iraqi Dinar)",
  "₪ (Israeli New Shekel)",
  "J\$ (Jamaican Dollar)",
  "¥ (Japanese Yen)",
  "د.ا (Jordanian Dinar)",
  "₸ (Kazakhstani Tenge)",
  "KSh (Kenyan Shilling)",
  "AU\$ (Australian Dollar)",
  "د.ك (Kuwaiti Dinar)",
  "som (Kyrgyzstani Som)",
  "₭ (Laotian Kip)",
  "ل.ل (Lebanese Pound)",
  "L (Lesotho Loti)",
  "L\$ (Liberian Dollar)",
  "ل.د (Libyan Dinar)",
  "CHF (Swiss Franc)",
  "Ar (Malagasy Ariary)",
  "MK (Malawian Kwacha)",
  "RM (Malaysian Ringgit)",
  "Rf (Maldivian Rufiyaa)",
  "Ouguiya (Mauritanian Ouguiya)",
  "Rs (Mauritian Rupee)",
  "Mex\$ (Mexican Peso)",
  "lei (Moldovan Leu)",
  "₮ (Mongolian Tugrik)",
  "د.م. (Moroccan Dirham)",
  "MT (Mozambican Metical)",
  "K (Myanmar Kyat)",
  "N\$ (Namibian Dollar)",
  "रू (Nepalese Rupee)",
  "NZ\$ (New Zealand Dollar)",
  "C\$ (Nicaraguan Córdoba)",
  "₦ (Nigerian Naira)",
  "kr (Norwegian Krone)",
  "﷼ (Omani Rial)",
  "PKR (Pakistani Rupee)",
  "₱ (Philippine Peso)",
  "zł (Polish Złoty)",
  "﷼ (Qatari Riyal)",
  "lei (Romanian Leu)",
  "руб (Russian Ruble)",
  "RF (Rwandan Franc)",
  "₣ (Swiss Franc)",
  "₲ (Paraguayan Guarani)",
  "SR (Saudi Riyal)",
  "د.س (Sudanese Pound)",
  "\$ (Singapore Dollar)",
  "S (Solomon Islands Dollar)",
  "Sh (Somali Shilling)",
  "R (South African Rand)",
  "₩ (South Korean Won)",
  "£ (British Pound)",
  "Rs (Sri Lankan Rupee)",
  "L (Saint Helenian Pound)",
  "\$ (East Caribbean Dollar)",
  "kr (Swedish Krona)",
  "TJS (Tajikistani Somoni)",
  "TSh (Tanzanian Shilling)",
  "฿ (Thai Baht)",
  "T (Tongan Paʻanga)",
  "TTD (Trinidad and Tobago Dollar)",
  "XAf (XAf Central Africa)",
];

String constUserId = '';
bool isSubUser = false;
String subUserTitle = '';
String subUserEmail = '';
bool isSubUserDeleted = true;
//
String userPermissionErrorText = 'Access not granted';

UserRoleModel finalUserRoleModel = UserRoleModel();

class CurrentUserData {
  Future<void> getUserData() async {
    final prefs = await SharedPreferences.getInstance();
    constUserId = prefs.getString('userId') ?? '';
    print('-------------user id $constUserId----------------');
    isSubUser = prefs.getBool('isSubUser') ?? false;
    subUserEmail = prefs.getString('subUserEmail') ?? '';
    await updateData();
  }

  Future<void> updateData() async {
    final prefs = await SharedPreferences.getInstance();
    final ref = FirebaseDatabase.instance.ref(constUserId).child('User Role');
    ref.keepSynced(true);
    ref.orderByKey().get().then(
      (value) async {
        for (var element in value.children) {
          var data = UserRoleModel.fromJson(jsonDecode(jsonEncode(element.value)));
          print(data.toJson());
          if (data.userEmail == subUserEmail) {
            isSubUserDeleted = false;
            finalUserRoleModel = data;
            await prefs.setString('userTitle', data.userTitle ?? '');
            subUserTitle = prefs.getString('userTitle') ?? '';
          }
        }
      },
    );
  }

  Future<bool> isSubUserEmailNotFound() async {
    bool isMailMatch = true;
    final ref = FirebaseDatabase.instance.ref(constUserId).child('User Role');
    ref.keepSynced(true);

    await ref.orderByKey().get().then((value) async {
      for (var element in value.children) {
        var data = UserRoleModel.fromJson(jsonDecode(jsonEncode(element.value)));
        if (data.userEmail == subUserEmail) {
          isMailMatch = false;
          return;
        }
      }
    });
    return isMailMatch;
  }

  Future<void> putUserData(
      {required String userId,
      required bool subUser,
      required String title,
      required String email}) async {
    final prefs = await SharedPreferences.getInstance();
    constUserId = userId;
    isSubUser = subUser;

    await prefs.setString('userId', userId);
    await prefs.setString('subUserEmail', email);
    await prefs.setString('userTitle', title);
    await prefs.setBool('isSubUser', subUser);
    getUserData();
  }
}

Future<bool> checkUserRolePermission({required String type}) async {
  await CurrentUserData().getUserData();
  bool permission = true;
  print(finalUserRoleModel.productUpdate);
  if (isSubUser) {
    switch (type) {
      //-----------For Home Page----------------
      case "Sales":
        permission = finalUserRoleModel.posSaleCreate ?? false;
        break;
      case "Parties":
        permission = (finalUserRoleModel.supplierListRead ?? false) ||
            (finalUserRoleModel.customerListRead ?? false);
        break;
      case "Purchase":
        permission = finalUserRoleModel.purchaseCreate ?? false;
        break;
      case "Product":
        permission = finalUserRoleModel.productRead ?? false;
        break;
      case "Quotation":
        permission = finalUserRoleModel.quotationListRead ?? false;
        break;
      case "Due List":
        permission = finalUserRoleModel.dueListRead ?? false;
        break;
      case "Stocks":
        permission = finalUserRoleModel.stockListRead ?? false;
        break;
      case "Reports":
        permission = finalUserRoleModel.allReportsRead ?? false;
        break;
      case "Sales List":
        permission = finalUserRoleModel.saleListRead ?? false;
        break;
      case "Purchase List":
        permission = finalUserRoleModel.purchaseRead ?? false;
        break;
      case "Loss/Profit":
        permission = finalUserRoleModel.lossProfitRead ?? false;
        break;
      case "Ledger":
        permission = finalUserRoleModel.ledgerRead ?? false;
        break;
      case "Expense":
        permission = finalUserRoleModel.expenseRead ?? false;
        break;
      case "Tax Report":
        permission = finalUserRoleModel.taxRateRead ?? false;
        break;
      case "HRM":
        permission = finalUserRoleModel.hrmRead ?? false;
        break;
      //---------------add new features-------------------
      case 'dashboard-read':
        permission = finalUserRoleModel.dashboardRead ?? false;
        break;
      //----------pos sale----------------------------
      case 'pos-sale-read':
        permission = finalUserRoleModel.posSaleRead ?? false;
        break;
      case 'pos-sale-create':
        permission = finalUserRoleModel.posSaleCreate ?? false;
        break;
      case 'pos-sale-update':
        permission = finalUserRoleModel.posSaleUpdate ?? false;
        break;
      case 'pos-sale-delete':
        permission = finalUserRoleModel.posSaleDelete ?? false;
        break;
      //----------inventory sale----------------------------
      case 'inventory-sale-read':
        permission = finalUserRoleModel.inventorySaleRead ?? false;
        break;
      case 'inventory-sale-create':
        permission = finalUserRoleModel.inventorySaleCreate ?? false;
        break;
      case 'inventory-sale-update':
        permission = finalUserRoleModel.inventorySaleUpdate ?? false;
        break;
      case 'inventory-sale-delete':
        permission = finalUserRoleModel.inventorySaleDelete ?? false;
        break;
      //----------sale list----------------------------
      case 'sale-list-read':
        permission = finalUserRoleModel.saleListRead ?? false;
        break;
      case 'sale-list-create':
        permission = finalUserRoleModel.saleListCreate ?? false;
        break;
      case 'sale-list-update':
        permission = finalUserRoleModel.saleListUpdate ?? false;
        break;
      case 'sale-list-delete':
        permission = finalUserRoleModel.saleListDelete ?? false;
        break;
      //----------sale return----------------------------
      case 'sale-return-read':
        permission = finalUserRoleModel.saleReturnRead ?? false;
        break;
      case 'sale-return-create':
        permission = finalUserRoleModel.saleReturnCreate ?? false;
        break;
      case 'sale-return-update':
        permission = finalUserRoleModel.saleReturnUpdate ?? false;
        break;
      case 'sale-return-delete':
        permission = finalUserRoleModel.saleReturnDelete ?? false;
        break;
      //----------quotation list----------------------------
      case 'quotation-read':
        permission = finalUserRoleModel.quotationListRead ?? false;
        break;
      case 'quotation-create':
        permission = finalUserRoleModel.quotationListCreate ?? false;
        break;
      case 'quotation-update':
        permission = finalUserRoleModel.quotationListUpdate ?? false;
        break;
      case 'quotation-delete':
        permission = finalUserRoleModel.quotationListDelete ?? false;
        break;
      //----------purchase list----------------------------
      case 'purchase-read':
        permission = finalUserRoleModel.purchaseRead ?? false;
        break;
      case 'purchase-create':
        permission = finalUserRoleModel.purchaseCreate ?? false;
        break;
      case 'purchase-update':
        permission = finalUserRoleModel.purchaseUpdate ?? false;
        break;
      case 'purchase-delete':
        permission = finalUserRoleModel.purchaseDelete ?? false;
        break;
      //----------purchase return----------------------------
      case 'purchase-return-read':
        permission = finalUserRoleModel.purchaseReturnRead ?? false;
        break;
      case 'purchase-return-create':
        permission = finalUserRoleModel.purchaseReturnCreate ?? false;
        break;
      case 'purchase-return-update':
        permission = finalUserRoleModel.purchaseReturnUpdate ?? false;
        break;
      case 'purchase-return-delete':
        permission = finalUserRoleModel.purchaseReturnDelete ?? false;
        break;
      //----------product list----------------------------
      case 'product-read':
        permission = finalUserRoleModel.productRead ?? false;
        break;
      case 'product-create':
        permission = finalUserRoleModel.productCreate ?? false;
        break;
      case 'product-update':
        permission = finalUserRoleModel.productUpdate ?? false;
        break;
      case 'product-delete':
        permission = finalUserRoleModel.productDelete ?? false;
        break;
      //----------low stock----------------------------
      case 'low-stock-read':
        permission = finalUserRoleModel.lowStockRead ?? false;
        break;
      case 'low-stock-create':
        permission = finalUserRoleModel.lowStockCreate ?? false;
        break;
      case 'low-stock-update':
        permission = finalUserRoleModel.lowStockUpdate ?? false;
        break;
      case 'low-stock-delete':
        permission = finalUserRoleModel.lowStockDelete ?? false;
        break;
      //----------expired----------------------------
      case 'expired-read':
        permission = finalUserRoleModel.expiredRead ?? false;
        break;
      case 'expired-create':
        permission = finalUserRoleModel.expiredCreate ?? false;
        break;
      case 'expired-update':
        permission = finalUserRoleModel.expiredUpdate ?? false;
        break;
      case 'expired-delete':
        permission = finalUserRoleModel.expiredDelete ?? false;
        break;
      //----------categories----------------------------
      case 'categories-read':
        permission = finalUserRoleModel.categoriesRead ?? false;
        break;
      case 'categories-create':
        permission = finalUserRoleModel.categoriesCreate ?? false;
        break;
      case 'categories-update':
        permission = finalUserRoleModel.categoriesUpdate ?? false;
        break;
      case 'categories-delete':
        permission = finalUserRoleModel.categoriesDelete ?? false;
        break;

      //----------brand----------------------------
      case 'brand-read':
        permission = finalUserRoleModel.brandRead ?? false;
        break;
      case 'brand-create':
        permission = finalUserRoleModel.brandCreate ?? false;
        break;
      case 'brand-update':
        permission = finalUserRoleModel.brandUpdate ?? false;
        break;
      case 'brand-delete':
        permission = finalUserRoleModel.brandDelete ?? false;
        break;
      //----------unit-------------------------------------------
      case 'unit-read':
        permission = finalUserRoleModel.unitRead ?? false;
        break;
      case 'unit-create':
        permission = finalUserRoleModel.unitCreate ?? false;
        break;
      case 'unit-update':
        permission = finalUserRoleModel.unitUpdate ?? false;
        break;
      case 'unit-delete':
        permission = finalUserRoleModel.unitDelete ?? false;
        break;
      //----------ware house----------------------------------
      case 'ware-house-read':
        permission = finalUserRoleModel.wareHouseRead ?? false;
        break;
      case 'ware-house-create':
        permission = finalUserRoleModel.wareHouseCreate ?? false;
        break;
      case 'ware-house-update':
        permission = finalUserRoleModel.wareHouseUpdate ?? false;
        break;
      case 'ware-house-delete':
        permission = finalUserRoleModel.wareHouseDelete ?? false;
        break;
      //----------supplier list----------------------------------
      case 'supplier-list-read':
        permission = finalUserRoleModel.supplierListRead ?? false;
        break;
      case 'supplier-list-create':
        permission = finalUserRoleModel.supplierListCreate ?? false;
        break;
      case 'supplier-list-update':
        permission = finalUserRoleModel.supplierListUpdate ?? false;
        break;
      case 'supplier-list-delete':
        permission = finalUserRoleModel.supplierListDelete ?? false;
        break;
      //----------customer list----------------------------------
      case 'customer-list-read':
        permission = finalUserRoleModel.customerListRead ?? false;
        break;
      case 'customer-list-create':
        permission = finalUserRoleModel.customerListCreate ?? false;
        break;
      case 'customer-list-update':
        permission = finalUserRoleModel.customerListUpdate ?? false;
        break;
      case 'customer-list-delete':
        permission = finalUserRoleModel.customerListDelete ?? false;
        break;
      //----------due list----------------------------------
      case 'due-list-read':
        permission = finalUserRoleModel.dueListRead ?? false;
        break;
      case 'due-list-create':
        permission = finalUserRoleModel.dueListCreate ?? false;
        break;
      case 'due-list-update':
        permission = finalUserRoleModel.dueListUpdate ?? false;
        break;
      case 'due-list-delete':
        permission = finalUserRoleModel.dueListDelete ?? false;
        break;
      //----------ledger----------------------------------
      case 'ledger-read':
        permission = finalUserRoleModel.ledgerRead ?? false;
        break;
      case 'ledger-create':
        permission = finalUserRoleModel.ledgerCreate ?? false;
        break;
      case 'ledger-update':
        permission = finalUserRoleModel.ledgerUpdate ?? false;
        break;
      case 'ledger-delete':
        permission = finalUserRoleModel.ledgerDelete ?? false;
        break;
      //----------loss profit----------------------------------
      case 'loss-profit-read':
        permission = finalUserRoleModel.lossProfitRead ?? false;
        break;
      case 'loss-profit-create':
        permission = finalUserRoleModel.lossProfitCreate ?? false;
        break;
      case 'loss-profit-update':
        permission = finalUserRoleModel.lossProfitUpdate ?? false;
        break;

      case 'loss-profit-delete':
        permission = finalUserRoleModel.lossProfitDelete ?? false;
        break;
      //----------payment type----------------------------------
      case 'payment-type-read':
        permission = finalUserRoleModel.paymentTypeRead ?? false;
        break;
      case 'payment-type-create':
        permission = finalUserRoleModel.paymentTypeCreate ?? false;
        break;
      case 'payment-type-update':
        permission = finalUserRoleModel.paymentTypeUpdate ?? false;
        break;
      case 'payment-type-delete':
        permission = finalUserRoleModel.paymentTypeDelete ?? false;
        break;

      //----------expense----------------------------------
      case 'expense-read':
        permission = finalUserRoleModel.expenseRead ?? false;
        break;
      case 'expense-create':
        permission = finalUserRoleModel.expenseCreate ?? false;
        break;
      case 'expense-update':
        permission = finalUserRoleModel.expenseUpdate ?? false;
        break;
      case 'expense-delete':
        permission = finalUserRoleModel.expenseDelete ?? false;
        break;
      //----------expense category----------------------------------
      case 'expense-category-read':
        permission = finalUserRoleModel.expenseCategoryRead ?? false;
        break;
      case 'expense-category-create':
        permission = finalUserRoleModel.expenseCategoryCreate ?? false;
        break;
      case 'expense-category-update':
        permission = finalUserRoleModel.expenseCategoryUpdate ?? false;
        break;

      case 'expense-category-delete':
        permission = finalUserRoleModel.expenseCategoryDelete ?? false;
        break;
      //----------income----------------------------------
      case 'income-read':
        permission = finalUserRoleModel.incomeRead ?? false;
        break;
      case 'income-create':
        permission = finalUserRoleModel.incomeCreate ?? false;
        break;
      case 'income-update':
        permission = finalUserRoleModel.incomeUpdate ?? false;
        break;
      case 'income-delete':
        permission = finalUserRoleModel.incomeDelete ?? false;
        break;
      //----------income category
      case 'income-category-read':
        permission = finalUserRoleModel.incomeCategoryRead ?? false;
        break;
      case 'income-category-create':
        permission = finalUserRoleModel.incomeCategoryCreate ?? false;
        break;
      case 'income-category-update':
        permission = finalUserRoleModel.incomeCategoryUpdate ?? false;
        break;

      case 'income-category-delete':
        permission = finalUserRoleModel.incomeCategoryDelete ?? false;
        break;
      //----------transaction------------------------------------
      case 'transaction-read':
        permission = finalUserRoleModel.transactionRead ?? false;
        break;
      case 'transaction-create':
        permission = finalUserRoleModel.transactionCreate ?? false;
        break;
      case 'transaction-update':
        permission = finalUserRoleModel.transactionUpdate ?? false;
        break;
      case 'transaction-delete':
        permission = finalUserRoleModel.transactionDelete ?? false;
        break;
      //----------all reports------------------------------------
      case 'all-reports-read':
        permission = finalUserRoleModel.allReportsRead ?? false;
        break;
      case 'all-reports-create':
        permission = finalUserRoleModel.allReportsCreate ?? false;
        break;
      case 'all-reports-update':
        permission = finalUserRoleModel.allReportsUpdate ?? false;
        break;
      case 'all-reports-delete':
        permission = finalUserRoleModel.allReportsDelete ?? false;
        break;
      //-----------------whatsapp marketing-----------------------
      case 'whatsapp-marketing-read':
        permission = finalUserRoleModel.whatsAppMarketingRead ?? false;
        break;
      case 'whatsapp-marketing-create':
        permission = finalUserRoleModel.whatsAppMarketingCreate ?? false;
        break;
      case 'whatsapp-marketing-update':
        permission = finalUserRoleModel.whatsAppMarketingUpdate ?? false;
        break;
      case 'whatsapp-marketing-delete':
        permission = finalUserRoleModel.whatsAppMarketingDelete ?? false;
        break;
      //--------------stock list--------------------------
      case 'stock-list-read':
        permission = finalUserRoleModel.stockListRead ?? false;
        break;
      case 'stock-list-create':
        permission = finalUserRoleModel.stockListCreate ?? false;
        break;
      case 'stock-list-update':
        permission = finalUserRoleModel.stockListUpdate ?? false;
        break;
      case 'stock-list-delete':
        permission = finalUserRoleModel.stockListDelete ?? false;
        break;
      //--------------subscription--------------------------
      case 'subscription-read':
        permission = finalUserRoleModel.subscriptionRead ?? false;
        break;
      case 'subscription-create':
        permission = finalUserRoleModel.subscriptionCreate ?? false;
        break;
      case 'subscription-update':
        permission = finalUserRoleModel.subscriptionUpdate ?? false;
        break;
      case 'subscription-delete':
        permission = finalUserRoleModel.subscriptionDelete ?? false;
        break;
      //--------------user role--------------------------
      case 'user-role-read':
        permission = finalUserRoleModel.userRoleRead ?? false;
        break;
      case 'user-role-create':
        permission = finalUserRoleModel.userRoleCreate ?? false;
        break;
      case 'user-role-update':
        permission = finalUserRoleModel.userRoleUpdate ?? false;
        break;
      case 'user-role-delete':
        permission = finalUserRoleModel.userRoleDelete ?? false;
        break;
      //--------------tax rate--------------------------
      case 'tax-rate-read':
        permission = finalUserRoleModel.taxRateRead ?? false;
        break;
      case 'tax-rate-create':
        permission = finalUserRoleModel.taxRateCreate ?? false;
        break;
      case 'tax-rate-update':
        permission = finalUserRoleModel.taxRateUpdate ?? false;
        break;
      case 'tax-rate-delete':
        permission = finalUserRoleModel.taxRateDelete ?? false;
        break;
      //--------------hrm--------------------------
      case 'hrm-read':
        permission = finalUserRoleModel.hrmRead ?? false;
        break;
      case 'hrm-create':
        permission = finalUserRoleModel.hrmCreate ?? false;
        break;
      case 'hrm-update':
        permission = finalUserRoleModel.hrmUpdate ?? false;
        break;
      case 'hrm-delete':
        permission = finalUserRoleModel.hrmDelete ?? false;
        break;
      default:
        permission = true;
        break;
    }

    if (permission) {
      return permission;
    } else {
      EasyLoading.showError('You don\'t have permission to access this page');
      return permission;
    }
  } else {
    return true;
  }
}

bool newSelect = false;
