import 'dart:convert';

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:intl/intl.dart';
import 'package:nb_utils/nb_utils.dart';
import 'package:restart_app/restart_app.dart';

import 'Screen/tax rates/tax_model.dart';
import 'model/add_to_cart_model.dart';
import 'model/sale_transaction_model.dart';
import 'model/user_role_model.dart';

///______________DATA____________
String appsName = 'POS SAAS';
String appsTitle = 'POS SAAS Web';
String pdfFooter = 'Acnoo';
String madeBy = 'Acnoo.com';
bool isDemo = false;
String invoiceFileName = "POS_SAAS";
String demoText = 'You Can\'t change anything in demo mode';
String sideBarLogo = 'images/pos.png';
String appLogo = 'images/mobipos.png';
bool isTwillio = true;
bool isUltraMsg = false;
String nameLogo = 'images/namelogo.svg';
String currentDomain = 'https://possaasweb.acnoo.com';

///____________Purchase_C0de_______________________________________
String purchaseCode = 'Enter your purchase code';

String calculateProductVat({required AddToCartModel product}) {
  if (product.taxType == 'Inclusive') {
    //double taxAmount = purchasePrice / (1 + taxRate) * taxRate;
    double taxRate = product.groupTaxRate / 100;
    print(product.groupTaxRate);
    return (((double.tryParse(product.productPurchasePrice.toString()) ?? 0) / (taxRate + 1) * taxRate) * product.quantity).toStringAsFixed(1);
  } else {
    return (((product.groupTaxRate * (double.tryParse(product.productPurchasePrice.toString()) ?? 0)) / 100) * product.quantity).toStringAsFixed(1);
  }
}

SaleTransactionModel checkLossProfit({required SaleTransactionModel transitionModel}) {
  double calculateAmountFromPercentage(double percentage, double price) {
    return (percentage * price) / 100;
  }

  num totalQuantity = 0;
  double lossProfit = 0;
  double totalPurchasePrice = 0;
  double totalSalePrice = 0;
  for (var element in transitionModel.productList!) {
    if (element.taxType == 'Exclusive') {
      double tax = calculateAmountFromPercentage(element.groupTaxRate.toDouble(), (double.tryParse(element.productPurchasePrice.toString()) ?? 0));
      totalPurchasePrice = totalPurchasePrice + ((((double.tryParse(element.productPurchasePrice.toString()) ?? 0) + tax) * element.quantity));
    } else {
      totalPurchasePrice = totalPurchasePrice + ((double.tryParse(element.productPurchasePrice.toString()) ?? 0) * element.quantity);
    }

    totalSalePrice = totalSalePrice + (double.parse(element.subTotal) * element.quantity);

    totalQuantity = totalQuantity + element.quantity;
  }
  lossProfit = ((totalSalePrice - totalPurchasePrice.toDouble()) - double.parse(transitionModel.discountAmount.toString()));

  transitionModel.totalQuantity = totalQuantity;
  transitionModel.lossProfit = double.parse(lossProfit.toStringAsFixed(2));

  return transitionModel;
}

List<TaxModel> getAllTaxFromCartList({required List<AddToCartModel> cart}) {
  List<TaxModel> data = [];
  for (var element in cart) {
    if (element.subTaxes.isNotEmpty) {
      for (var element1 in element.subTaxes) {
        if (!data.any(
          (element2) => element2.name == element1.name,
        )) {
          data.add(element1);
        }
      }
    }
  }
  return data;
}

final GlobalKey<RefreshIndicatorState> _refreshIndicatorKey = GlobalKey<RefreshIndicatorState>();

// String appLogo='images/mobipos.png';
// String appsName = 'Pos Saas';
// String appsTitle = 'Pos Saas Web';
// String pdfFooter = 'POSBharat.com';
// bool isDemo = false;
// String demoText = 'You Can\'t change anything in demo mode';
// String sideBarLogo='images/pos.png';

List<String> selectedNumbers = [];

Future<String?> getSaleID({required String id}) async {
  String? key;
  await FirebaseDatabase.instance.ref().child('Admin Panel').child('Seller List').orderByKey().get().then((value) async {
    for (var element in value.children) {
      var data = jsonDecode(jsonEncode(element.value));
      if (data['userId'].toString() == id) {
        key = element.key.toString();
      }
    }
  });
  return key;
}

String constUserId = '';
bool isSubUser = false;
String constSubUserTitle = '';

String subUserEmail = '';

String searchItems = '';

String mainLoginPassword = '';
String mainLoginEmail = '';

UserRoleModel finalUserRoleModel = UserRoleModel();

Future<void> setUserDataOnLocalData({required String uid, required String subUserTitle, required bool isSubUser, String? email, String? password}) async {
  final prefs = await SharedPreferences.getInstance();
  await prefs.setString('userId', uid);
  await prefs.setString('subUserTitle', subUserTitle);
  await prefs.setBool('isSubUser', isSubUser);
  if (email != null) {
    await prefs.setString('userEmail', email);
  }
  if (password != null) {
    await prefs.setString('userPassword', password);
  }
}

Future<void> getUserDataFromLocal() async {
  final prefs = await SharedPreferences.getInstance();
  constUserId = prefs.getString('userId') ?? '';
  constSubUserTitle = prefs.getString('subUserTitle') ?? '';
  isSubUser = prefs.getBool('isSubUser') ?? false;
  String? data = prefs.getString("userPermission");
  data != null ? finalUserRoleModel = UserRoleModel.fromJson(jsonDecode(data)) : null;
}

String userPermissionErrorText = 'Access not granted';

Future<bool> checkUserRolePermission({required String type}) async {
  await getUserDataFromLocal();
  bool permission = true;

  if (isSubUser) {
    switch (type) {
      //---------------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;
  }
}

Future<String> getUserID() async {
  final prefs = await SharedPreferences.getInstance();
  final String? uid = prefs.getString('userId');
  print('--------------------get user id $uid-------------------');
  return uid ?? '';
}

void putUserDataImidiyate({required String uid, required String title, required bool isSubUse}) {
  constUserId = uid;
  constSubUserTitle = title;
  isSubUser = isSubUse;
}

List<String> categories = [
  'Select Business Category',
  'Bag & Luggage',
  'Books & Stationery',
  'Clothing',
  'Construction & Raw materials',
  'Coffee & Tea',
  'Cosmetic & Jewellery',
  'Computer & Electronic',
  'E-Commerce',
  'Furniture',
  'General Store',
  'Gift, Toys & flowers',
  'Grocery, Fruits & Bakery',
  'Handicraft',
  'Home & Kitchen',
  'Hardware & sanitary',
  'Internet, Dish & TV',
  'Laundry',
  'Manufacturing',
  'Mobile Top up',
  'Motorbike & parts',
  'Mobile & Gadgets',
  'Pharmacy',
  'Poultry & Agro',
  'Pet & Accessories',
  'Rice mill',
  'Super Shop',
  'Sunglasses',
  'Service & Repairing',
  'Sports & Exercise',
  'Shoes',
  'Saloon & Beauty Parlour',
  'Shop Rent & Office Rent',
  'Trading',
  'Travel Ticket & Rental',
  'Thai Aluminium & Glass',
  'Vehicles & Parts',
  'Others',
];
String dropdownValue = 'Select Business Category';

final currentDate = DateTime.now();
final firstDayOfCurrentMonth = DateTime(currentDate.year, currentDate.month, 1);
final firstDayOfCurrentYear = DateTime(currentDate.year, 1, 1);
final firstDayOfPreviousYear = firstDayOfCurrentYear.subtract(const Duration(days: 1));
final lastDayOfPreviousMonth = firstDayOfCurrentMonth.subtract(const Duration(days: 1));
final firstDayOfPreviousMonth = DateTime(lastDayOfPreviousMonth.year, lastDayOfPreviousMonth.month, 1);

DateFormat dataTypeFormat = DateFormat('dd MMM yyyy');

double safeParseDouble(String? value) {
  return double.tryParse(value ?? '0') ?? 0;
}

void checkCurrentUserAndRestartApp() {
  final User? user = FirebaseAuth.instance.currentUser;
  if (user?.uid == null) {
    Restart.restartApp();
  }
}

String formatPointNumber(num value, {bool addComma = false}) {
  String formatted;

  if (value % 1 == 0) {
    formatted = value.toInt().toString();
  } else {
    formatted = value.toStringAsFixed(2);
  }

  if (addComma) {
    // NumberFormat from intl package is used here
    final formatter = NumberFormat.decimalPattern();
    formatted = formatter.format(num.parse(formatted));
  }

  return formatted;
}
