import 'dart:io';

import 'package:android_intent_plus/android_intent.dart';
import 'package:digi_bank/src/app/constants/app_colors.dart';
import 'package:digi_bank/src/app/routes/routes.dart';
import 'package:digi_bank/src/common/controller/languages_controller.dart';
import 'package:digi_bank/src/common/controller/theme/theme_controller.dart';
import 'package:digi_bank/src/common/model/user_model.dart';
import 'package:digi_bank/src/common/services/biometric_auth_service.dart';
import 'package:digi_bank/src/common/services/settings_service.dart';
import 'package:digi_bank/src/common/widgets/common_elevated_button.dart';
import 'package:digi_bank/src/network/api/api_path.dart';
import 'package:digi_bank/src/network/response/status.dart';
import 'package:digi_bank/src/network/service/network_service.dart';
import 'package:digi_bank/src/network/service/token_service.dart';
import 'package:digi_bank/src/presentation/screens/home/model/dashboard_model.dart';
import 'package:digi_bank/src/presentation/screens/home/model/navigations_model.dart';
import 'package:digi_bank/src/utils/helpers/language_storage.dart';
import 'package:flutter/material.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:get/get.dart';
import 'package:local_auth/local_auth.dart';

class HomeController extends GetxController {
  final LanguagesController languagesController = Get.put(
    LanguagesController(),
  );
  final RxBool isLoading = false.obs;
  final RxBool isSettingsLoading = false.obs;
  final RxBool isDeleteAccountLoading = false.obs;
  final RxBool isDashboardLoading = false.obs;
  final RxBool isNavigationsLoading = false.obs;
  final RxBool isBiometricEnable = false.obs;
  final RxString language = "".obs;
  final languageController = TextEditingController();
  GlobalKey<ScaffoldState>? _scaffoldKey;
  final RxBool isSwitchMode = false.obs;
  final RxBool isVisibleBalance = true.obs;
  final RxInt selectedIndex = 1.obs;
  final Rx<DashboardModel> dashboardModel = DashboardModel().obs;
  final Rx<UserModel> userModel = UserModel().obs;
  final RxList<NavigationsData> navigationsList = <NavigationsData>[].obs;
  final reasonController = TextEditingController();
  final RxString passcodeVerification = "".obs;
  final RxString faVerification = "".obs;
  final RxString kycVerification = "".obs;
  final RxString languageSwitcher = "".obs;
  final RxString multipleCurrency = "".obs;
  final RxString virtualCard = "".obs;
  final RxString userDeposit = "".obs;
  final RxString userDps = "".obs;
  final RxString userFdr = "".obs;
  final RxString userLoan = "".obs;
  final RxString userReward = "".obs;
  final RxString userPortfolio = "".obs;
  final RxString userWithdraw = "".obs;
  final RxString transferStatus = "".obs;
  final RxString userPayBill = "".obs;
  final RxString signUpReferral = "".obs;

  @override
  void onInit() {
    super.onInit();
    loadData();
    loadBiometricStatus();
  }

  Future<void> loadBiometricStatus() async {
    final savedBiometric = await SettingsService.getBiometricEnableOrDisable();
    isBiometricEnable.value = savedBiometric ?? false;
  }

  Future<void> toggleBiometric() async {
    final LocalAuthentication auth = LocalAuthentication();
    final biometricAuthService = BiometricAuthService();
    final isSupported = await auth.isDeviceSupported();
    final isAvailable = await biometricAuthService.isBiometricAvailable();

    if (!isSupported) {
      Fluttertoast.showToast(
        msg: "This device does not support biometrics.",
        backgroundColor: AppColors.error,
      );
      return;
    }
    if (!isAvailable) {
      _showBiometricNotAvailableDialog();
      return;
    }

    final isAuthenticated =
        await biometricAuthService.authenticateWithBiometrics();

    if (isAuthenticated) {
      isBiometricEnable.value = !isBiometricEnable.value;
      await Get.find<SettingsService>().saveBiometricEnableOrDisable(
        isBiometricEnable.value,
      );

      Fluttertoast.showToast(
        msg:
            isBiometricEnable.value
                ? "Biometric enabled successfully"
                : "Biometric disabled successfully",
        backgroundColor: AppColors.success,
      );
    } else {
      Fluttertoast.showToast(
        msg: "Authentication failed. Biometric setting not changed.",
        backgroundColor: AppColors.error,
      );
    }
  }

  Future<void> loadData() async {
    isDashboardLoading.value = true;
    final languageSwitcherValue = await SettingsService.getSettingValue(
      'language_switcher',
    );
    languageSwitcher.value = languageSwitcherValue ?? "";
    final faVerificationValue = await SettingsService.getSettingValue(
      'fa_verification',
    );
    faVerification.value = faVerificationValue ?? "";
    final passcodeVerificationValue = await SettingsService.getSettingValue(
      'passcode_verification',
    );
    passcodeVerification.value = passcodeVerificationValue ?? "";
    final kycVerificationValue = await SettingsService.getSettingValue(
      'kyc_verification',
    );
    kycVerification.value = kycVerificationValue ?? "";
    final multipleCurrencyValue = await SettingsService.getSettingValue(
      'multiple_currency',
    );
    multipleCurrency.value = multipleCurrencyValue ?? "";
    final virtualCardValue = await SettingsService.getSettingValue(
      'virtual_card',
    );
    virtualCard.value = virtualCardValue ?? "";
    final userDepositValue = await SettingsService.getSettingValue(
      'user_deposit',
    );
    userDeposit.value = userDepositValue ?? "";
    final userDpsValue = await SettingsService.getSettingValue('user_dps');
    userDps.value = userDpsValue ?? "";
    final userFdrValue = await SettingsService.getSettingValue('user_fdr');
    userFdr.value = userFdrValue ?? "";
    final userLoanValue = await SettingsService.getSettingValue('user_loan');
    userLoan.value = userLoanValue ?? "";
    final userRewardValue = await SettingsService.getSettingValue(
      'user_reward',
    );
    userReward.value = userRewardValue ?? "";
    final userUserPortfolioValue = await SettingsService.getSettingValue(
      'user_portfolio',
    );
    userPortfolio.value = userUserPortfolioValue ?? "";
    final userWithdrawValue = await SettingsService.getSettingValue(
      'user_withdraw',
    );
    userWithdraw.value = userWithdrawValue ?? "";
    final transferStatusValue = await SettingsService.getSettingValue(
      'transfer_status',
    );
    transferStatus.value = transferStatusValue ?? "";
    final userPayBillValue = await SettingsService.getSettingValue(
      'user_pay_bill',
    );
    userPayBill.value = userPayBillValue ?? "";
    final signUpReferralValue = await SettingsService.getSettingValue(
      'sign_up_referral',
    );
    signUpReferral.value = signUpReferralValue ?? "";

    await fetchDashboard();
    await fetchUser();
    if (languageSwitcher.value != "0") {
      await languagesController.fetchLanguages();
    }
    await fetchNavigations();
    if (languageSwitcher.value != "0") {
      _setInitialLanguage();
    }
    isDashboardLoading.value = false;
  }

  Future<void> _setInitialLanguage() async {
    final savedLocale = await LanguageStorage.getSavedLocale();

    if (savedLocale != null) {
      final savedLanguage = languagesController.languagesList.firstWhere(
        (lang) => lang.locale == savedLocale,
      );

      language.value = savedLanguage.name!;
      languageController.text = savedLanguage.name!;
      languagesController.locale.value = savedLanguage.locale!;
    } else {
      final defaultLanguage = languagesController.languagesList.firstWhere(
        (lang) => lang.isDefault == 1,
      );

      language.value = defaultLanguage.name!;
      languageController.text = defaultLanguage.name!;
      languagesController.locale.value = defaultLanguage.locale!;
      await LanguageStorage.saveLocale(defaultLanguage.locale!);
    }
  }

  void setScaffoldKey(GlobalKey<ScaffoldState> key) {
    _scaffoldKey = key;
  }

  void openEndDrawer() {
    _scaffoldKey!.currentState!.openEndDrawer();
  }

  void openDrawer() {
    _scaffoldKey!.currentState!.openDrawer();
  }

  Future<void> fetchDashboard() async {
    try {
      final response = await Get.find<NetworkService>().get(
        endpoint: ApiPath.dashboardEndpoint,
      );
      if (response.status == Status.completed) {
        dashboardModel.value = DashboardModel.fromJson(response.data!);
      }
    } finally {}
  }

  Future<void> fetchUser() async {
    try {
      final response = await Get.find<NetworkService>().get(
        endpoint: ApiPath.userEndpoint,
      );
      if (response.status == Status.completed) {
        userModel.value = UserModel.fromJson(response.data!);
      }
    } finally {}
  }

  Future<void> fetchNavigations() async {
    try {
      final response = await Get.find<NetworkService>().get(
        endpoint: ApiPath.getNavigationsEndpoint,
      );
      if (response.status == Status.completed) {
        final navigationsModel = NavigationsModel.fromJson(response.data!);
        navigationsList.clear();
        navigationsList.assignAll(navigationsModel.data!);
      }
    } finally {}
  }

  Future<void> submitLogout() async {
    isLoading.value = true;
    try {
      final response = await Get.find<NetworkService>().post(
        endpoint: ApiPath.logoutEndpoint,
      );
      isLoading.value = false;
      if (response.status == Status.completed) {
        await Get.find<TokenService>().clearToken();
        Get.offAllNamed(BaseRoute.signIn);
      }
    } finally {
      isLoading.value = false;
    }
  }

  Future<void> submitCloseAccount() async {
    isDeleteAccountLoading.value = true;
    try {
      final Map<String, dynamic> requestBody = {
        "reason": reasonController.text,
      };

      final response = await Get.find<NetworkService>().post(
        endpoint: "${ApiPath.profileSettingsEndpoint}/account-close",
        data: requestBody,
      );

      if (response.status == Status.completed) {
        Fluttertoast.showToast(
          msg: response.data!["message"],
          backgroundColor: AppColors.success,
        );
        await submitLogout();
      }
    } finally {
      isDeleteAccountLoading.value = false;
    }
  }

  void toggleVisibleBalance() {
    isVisibleBalance.value = !isVisibleBalance.value;
  }

  void _showBiometricNotAvailableDialog() {
    final ThemeController themeController = Get.find<ThemeController>();

    Get.bottomSheet(
      Container(
        padding: const EdgeInsets.symmetric(horizontal: 20.0, vertical: 24.0),
        decoration: BoxDecoration(
          color:
              themeController.isDarkMode.value
                  ? AppColors.darkSecondary
                  : AppColors.white,
          borderRadius: const BorderRadius.only(
            topLeft: Radius.circular(24.0),
            topRight: Radius.circular(24.0),
          ),
        ),
        child: Column(
          mainAxisSize: MainAxisSize.min,
          children: [
            // Drag handle
            Container(
              width: 40,
              height: 4,
              margin: const EdgeInsets.only(bottom: 16.0),
              decoration: BoxDecoration(
                color: Colors.grey.shade400,
                borderRadius: BorderRadius.circular(10),
              ),
            ),

            // Icon
            Icon(
              Icons.fingerprint,
              size: 40,
              color:
                  themeController.isDarkMode.value
                      ? AppColors.darkPrimary
                      : AppColors.primary,
            ),
            const SizedBox(height: 12),

            // Title
            Text(
              "Biometric Not Found",
              style: TextStyle(
                fontSize: 18.0,
                fontWeight: FontWeight.w700,
                color:
                    themeController.isDarkMode.value
                        ? AppColors.darkTextPrimary
                        : AppColors.textPrimary,
              ),
            ),
            const SizedBox(height: 10.0),

            // Description
            Text(
              "No fingerprint or biometric is enrolled on this device. You can set it up from the system settings.",
              textAlign: TextAlign.center,
              style: TextStyle(
                fontSize: 14.0,
                height: 1.5,
                color:
                    themeController.isDarkMode.value
                        ? AppColors.darkTextTertiary
                        : AppColors.textTertiary,
              ),
            ),
            const SizedBox(height: 24.0),

            // Button
            CommonElevatedButton(
              width: double.infinity,
              buttonName: "Open Security Settings",
              onPressed: _openSecuritySettings,
            ),
            const SizedBox(height: 10.0),
          ],
        ),
      ),
      isDismissible: true,
      enableDrag: true,
    );
  }

  void _openSecuritySettings() {
    if (Platform.isAndroid) {
      final intent = AndroidIntent(
        action: 'android.settings.SECURITY_SETTINGS',
      );
      intent.launch();
    } else if (Platform.isIOS) {
      Fluttertoast.showToast(
        msg: "Please go to Settings > Face ID & Passcode to set up biometrics.",
        backgroundColor: AppColors.warning,
      );
    }
  }
}
