import 'package:digi_bank/src/app/constants/app_colors.dart';
import 'package:digi_bank/src/app/constants/assets_path/png/png_assets.dart';
import 'package:digi_bank/src/app/routes/routes.dart';
import 'package:digi_bank/src/common/controller/navigation/navigation_controller.dart';
import 'package:digi_bank/src/common/controller/theme/theme_controller.dart';
import 'package:digi_bank/src/common/widgets/common_loading.dart';
import 'package:digi_bank/src/presentation/screens/all_transaction/view/all_transaction.dart';
import 'package:digi_bank/src/presentation/screens/home/controller/home_controller.dart';
import 'package:digi_bank/src/utils/extensions/translation_extension.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';

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

  @override
  State<DrawerSection> createState() => _DrawerSectionState();
}

class _DrawerSectionState extends State<DrawerSection> {
  final HomeController homeController = Get.find<HomeController>();
  final ThemeController themeController = Get.find<ThemeController>();

  final Map<String, String> navigationIcons = {
    "dashboard": PngAssets.drawerDashboardIcon,
    "deposit": PngAssets.drawerDepositIcon,
    "wallets": PngAssets.drawerWalletIcon,
    "cards": PngAssets.drawerVirtualCardIcon,
    "fund_transfer": PngAssets.drawerFundTransferIcon,
    "dps": PngAssets.drawerDPSIcon,
    "fdr": PngAssets.drawerFDRIcon,
    "loan": PngAssets.drawerLoanIcon,
    "pay_bill": PngAssets.drawerPayBillIcon,
    "transactions": PngAssets.drawerTransactionIcon,
    "withdraw": PngAssets.drawerWithdrawIcon,
    "referral": PngAssets.drawerReferralIcon,
    "portfolio": PngAssets.drawerPortfolioIcon,
    "rewards": PngAssets.drawerRewardIcon,
    "support": PngAssets.drawerSupportIcon,
    "settings": PngAssets.drawerSettingsIcon,
    "logout": PngAssets.drawerSignOutIcon,
  };

  final Map<String, dynamic> navigationRoutes = {
    "dashboard": null,
    "deposit": BaseRoute.deposit,
    "wallets": BaseRoute.wallet,
    "cards": BaseRoute.virtualCard,
    "fund_transfer": BaseRoute.fundTransfer,
    "dps": BaseRoute.dpsPlan,
    "fdr": BaseRoute.fdrPlan,
    "loan": BaseRoute.loanPlan,
    "pay_bill": BaseRoute.payBill,
    "transactions": AllTransaction(),
    "withdraw": BaseRoute.withdraw,
    "referral": BaseRoute.referral,
    "portfolio": BaseRoute.portfolio,
    "rewards": BaseRoute.reward,
    "support": BaseRoute.helpAndSupport,
    "settings": BaseRoute.settings,
  };

  final Map<String, int> navigationIndexes = {
    "dashboard": 0,
    "deposit": 0,
    "wallets": 2,
    "cards": 1,
    "rewards": 3,
    "support": 4,
    "settings": 4,
  };

  Future<void> loadNavigations() async {
    homeController.isNavigationsLoading.value = true;
    await homeController.fetchNavigations();
    homeController.isNavigationsLoading.value = false;
  }

  @override
  Widget build(BuildContext context) {
    final isMultiCurrency = homeController.multipleCurrency.value == "1";
    final isVirtualCard = homeController.virtualCard.value == "1";
    final isUserDeposit = homeController.userDeposit.value == "1";
    final isUserDps = homeController.userDps.value == "1";
    final isUserFdr = homeController.userFdr.value == "1";
    final isUserLoan = homeController.userLoan.value == "1";
    final isUserReward = homeController.userReward.value == "1";
    final isUserPortfolio = homeController.userPortfolio.value == "1";
    final isUserWithdraw = homeController.userWithdraw.value == "1";
    final isTransferStatus = homeController.transferStatus.value == "1";
    final isUserPayBill = homeController.userPayBill.value == "1";
    final isSignUpReferral = homeController.signUpReferral.value == "1";

    final sortedNavigations =
        homeController.navigationsList.where((item) {
            final shouldShow = item.type != null && item.name != null;

            if (item.type == "wallets" && !isMultiCurrency) {
              return false;
            }
            if (item.type == "cards" && !isVirtualCard) {
              return false;
            }
            if (item.type == "deposit" && !isUserDeposit) {
              return false;
            }
            if (item.type == "dps" && !isUserDps) {
              return false;
            }
            if (item.type == "fdr" && !isUserFdr) {
              return false;
            }
            if (item.type == "loan" && !isUserLoan) {
              return false;
            }
            if (item.type == "rewards" && !isUserReward) {
              return false;
            }
            if (item.type == "portfolio" && !isUserPortfolio) {
              return false;
            }
            if (item.type == "withdraw" && !isUserWithdraw) {
              return false;
            }
            if (item.type == "fund_transfer" && !isTransferStatus) {
              return false;
            }
            if (item.type == "pay_bill" && !isUserPayBill) {
              return false;
            }
            if (item.type == "referral" && !isSignUpReferral) {
              return false;
            }

            return shouldShow;
          }).toList()
          ..sort((a, b) => (a.priority ?? 0).compareTo(b.priority ?? 0));

    return SafeArea(
      bottom: false,
      child: Drawer(
        width: 310,
        shape: const RoundedRectangleBorder(borderRadius: BorderRadius.zero),
        backgroundColor:
            themeController.isDarkMode.value
                ? AppColors.darkSecondary
                : AppColors.white,
        child: Column(
          children: [
            Stack(
              children: [
                Image.asset(
                  PngAssets.drawerFrame,
                  fit: BoxFit.contain,
                  width: double.infinity,
                ),
                Padding(
                  padding: const EdgeInsets.only(
                    left: 28,
                    top: 42,
                    bottom: 26,
                    right: 26,
                  ),
                  child: Row(
                    mainAxisAlignment: MainAxisAlignment.spaceBetween,
                    children: [
                      Text(
                        "home.drawer.title".trns(),
                        style: TextStyle(
                          fontWeight: FontWeight.w700,
                          fontSize: 18,
                          color: AppColors.white,
                        ),
                      ),
                      GestureDetector(
                        onTap: () => Get.back(),
                        child: Image.asset(
                          PngAssets.drawerCancelIcon,
                          color: AppColors.white,
                          width: 20,
                          fit: BoxFit.contain,
                        ),
                      ),
                    ],
                  ),
                ),
              ],
            ),
            Obx(
              () => Expanded(
                child:
                    homeController.isNavigationsLoading.value
                        ? CommonLoading()
                        : RefreshIndicator(
                          color:
                              themeController.isDarkMode.value
                                  ? AppColors.darkPrimary
                                  : AppColors.primary,
                          onRefresh: () => loadNavigations(),
                          child: ListView.separated(
                            padding: const EdgeInsets.symmetric(
                              horizontal: 28,
                              vertical: 20,
                            ),
                            itemBuilder: (context, index) {
                              final navigation = sortedNavigations[index];
                              final type = navigation.type;
                              final name = navigation.name;

                              return InkWell(
                                onTap: () {
                                  Get.back();
                                  final navigationController =
                                      Get.find<NavigationController>();

                                  if (type == "logout") {
                                    homeController.submitLogout();
                                  } else if (type == "dashboard") {
                                    navigationController.selectedIndex.value =
                                        navigationIndexes[type] ?? 0;
                                  } else if (type == "transactions") {
                                    navigationController.selectedIndex.value =
                                        navigationIndexes[type] ?? 0;
                                    navigationController.pushPage(
                                      navigationRoutes[type],
                                    );
                                  } else {
                                    navigationController.selectedIndex.value =
                                        navigationIndexes[type] ?? 0;
                                    navigationController.pushNamed(
                                      navigationRoutes[type],
                                    );
                                  }
                                },
                                child: Padding(
                                  padding: const EdgeInsets.symmetric(
                                    vertical: 11,
                                  ),
                                  child: Row(
                                    children: [
                                      Image.asset(
                                        navigationIcons[type]!,
                                        color:
                                            type == "logout"
                                                ? AppColors.error
                                                : themeController
                                                    .isDarkMode
                                                    .value
                                                ? AppColors.darkTextPrimary
                                                : AppColors.textPrimary,
                                        width: 20,
                                        fit: BoxFit.contain,
                                      ),
                                      const SizedBox(width: 10),
                                      Text(
                                        name!,
                                        style: TextStyle(
                                          fontWeight: FontWeight.w700,
                                          fontSize: 14,
                                          color:
                                              type == "logout"
                                                  ? AppColors.error
                                                  : themeController
                                                      .isDarkMode
                                                      .value
                                                  ? AppColors.darkTextPrimary
                                                  : AppColors.textPrimary,
                                        ),
                                      ),
                                    ],
                                  ),
                                ),
                              );
                            },
                            separatorBuilder:
                                (context, index) => const SizedBox(height: 10),
                            itemCount: sortedNavigations.length,
                          ),
                        ),
              ),
            ),
          ],
        ),
      ),
    );
  }
}
