import 'package:firebase_auth/firebase_auth.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:get/get.dart';
import 'package:hallo_doctor_doctor_app/app/models/transaction_model.dart';
import 'package:hallo_doctor_doctor_app/app/services/balance_service.dart';
import 'package:hallo_doctor_doctor_app/app/services/transaction_service.dart';

import '../../../models/user_wallet_model.dart';
import '../../../services/wallet_service.dart';

class BalanceController extends GetxController
    with StateMixin<List<Transaction>> {
  var balance = 0.obs;
  @override
  void onInit() async {
    super.onInit();
    initBalance();
  }

  initBalance() async {
    await getBalance();
    await getTransaction();
  }

  Future getTransaction() async {
    change([], status: RxStatus.loading());
    try {
      var transaction = await TransactionService().getAllTransaction();
      if (transaction.isEmpty) {
        change([], status: RxStatus.empty());
        return;
      }
      change(transaction, status: RxStatus.success());
    } catch (err) {
      change([], status: RxStatus.error());
    }
  }

  getBalance() async {
    try {
      var currentUser = FirebaseAuth.instance.currentUser;
      if (currentUser == null) {
        Fluttertoast.showToast(msg: 'User not authenticated');
        return;
      }

      // First attempt to get wallet
      UserWalletModel? userWallet =
          await UserWalletService().getUserWallet(currentUser.uid);

      if (userWallet == null) {
        // Wallet not found, try to create it
        try {
          await UserWalletService().requestCreateWallet(currentUser.uid);
          // After creation, try to get the wallet again
          userWallet = await UserWalletService().getUserWallet(currentUser.uid);

          if (userWallet == null) {
            // If still null after creation, show error
            balance.value = 0;
            Fluttertoast.showToast(
                msg: 'Failed to create wallet. Please try again later.');
            return;
          }
        } catch (createErr) {
          balance.value = 0;
          Fluttertoast.showToast(
              msg: 'Error creating wallet: ${createErr.toString()}');
          return;
        }
      }

      balance.value = userWallet.balance ?? 0;
    } catch (err) {
      balance.value = 0;
      Fluttertoast.showToast(msg: 'Error fetching balance: ${err.toString()}');
    }
  }

  withdraw() {
    Get.toNamed('/withdraw-method', arguments: balance.value);
  }
}
