// ignore_for_file: must_be_immutable

import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_mobx/flutter_mobx.dart';
import 'package:nb_utils/nb_utils.dart';
import '../../../network/rest_apis.dart';
import '../../../utils/colors.dart';
import '../../components/app_scaffold.dart';
import '../../components/loader_widget.dart';
import '../../components/price_widget.dart';
import '../../components/success_dialog.dart';
import '../../main.dart';
import '../../models/bank_list_response.dart';
import '../../utils/app_common.dart';
import '../../utils/common_base.dart';
import '../bankDetails/view/add_bank.dart';

class WithdrawRequest extends StatefulWidget {
  num availableBalance = 0;

  WithdrawRequest({super.key, required this.availableBalance});

  @override
  State<WithdrawRequest> createState() => _WithdrawRequestState();
}

class _WithdrawRequestState extends State<WithdrawRequest> {
  final GlobalKey<FormState> formKey = GlobalKey<FormState>();
  TextEditingController amount = TextEditingController();
  TextEditingController chooseBank = TextEditingController();

  FocusNode amountFocus = FocusNode();
  FocusNode chooseBankFocus = FocusNode();

  Future<List<BankHistory>>? future;
  List<BankHistory> bankHistoryList = [];
  BankHistory? selectedBank;

  int page = 1;
  bool isLastPage = false;

  @override
  void initState() {
    super.initState();
    init("");
  }

  init(String bankName) async {
    appStore.setLoading(true);
    getBankListDetail(
      page: page,
      list: bankHistoryList,
      lastPageCallback: (b) {
        isLastPage = b;
      },
      userId: userStore.userId,
    ).then((value) {
      setState(() {
        bankHistoryList = value;
      });
      bankHistoryList.forEach((value) {
        if (bankName.isNotEmpty && bankName == value.bankName) {
          setState(() {
            selectedBank = value;
          });
        } else if (value.isDefault == 1) {
          setState(() {
            selectedBank = value;
          });
        }
      });
    }).whenComplete(() {
      appStore.setLoading(false);
    });
  }

  withdrawMoney() {
    appStore.setLoading(true);
    Map request = {
      "_token": appStore.token.validate(),
      "payment_method": "bank",
      "payment_gateway": locale.wallet,
      "user_id": userStore.userId,
      "bank_id": selectedBank?.id,
      "amount": amount.text.toDouble(),
    };
    peoviderWithdrawMoney(request: request).then((value) {
      showDialog(
        context: context,
        builder: (BuildContext context) => SuccessDialog(
          title: locale.successful,
          description: locale.yourWithdrawalRequestHasBeenSuccessfullySubmitted,
          buttonText: locale.done,
        ),
      );
    }).catchError((e) {
      toast(e.toString());
    }).whenComplete(() {
      appStore.setLoading(false);
    });
  }

  @override
  void setState(fn) {
    if (mounted) super.setState(fn);
  }

  @override
  Widget build(BuildContext context) {
    return GestureDetector(
      onTap: () => hideKeyboard(context),
      child: AppScaffold(
        // appBarTitle: 'withdrawRequest',
        appBarWidget: commonAppBarWidget(
          context,
          title: locale.withdrawRequest,
          appBarHeight: 70,
          roundCornerShape: true,
          showLeadingIcon: true,
        ),
        body: Stack(
          children: [
            Form(
              key: formKey,
              child: AnimatedScrollView(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Container(
                    width: context.width(),
                    padding: EdgeInsets.all(16),
                    decoration: BoxDecoration(
                      borderRadius: BorderRadius.circular(8),
                      boxShadow: [
                        BoxShadow(
                          color: Colors.grey.withValues(alpha:0.1),
                          spreadRadius: 1,
                          blurRadius: 4,
                          offset: Offset(0, 1),
                        ),
                      ],
                    ),
                    child: Row(
                      mainAxisAlignment: MainAxisAlignment.spaceBetween,
                      children: [
                        Text(locale.availableBalance, style: secondaryTextStyle(size: 12)).expand(),
                        PriceWidget(price: widget.availableBalance.validate(), color: context.primaryColor, isBoldText: true),
                      ],
                    ),
                  ).paddingSymmetric(horizontal: 30),
                  24.height,
                  Text(locale.lblEnterAmount, style: primaryTextStyle(size: 12, weight: FontWeight.w600)),
                  8.height,
                  AppTextField(
                    textFieldType: TextFieldType.NUMBER,
                    controller: amount,
                    focus: amountFocus,
                    nextFocus: chooseBankFocus,
                    decoration: inputDecoration(context, hint: locale.eg3000),
                    inputFormatters: [FilteringTextInputFormatter.digitsOnly],
                    isValidationRequired: true,
                    validator: (value) {
                      if (value?.isEmpty ?? false) {
                        return errorThisFieldRequired;
                      } else if (num.parse(value.toString()) > num.parse(widget.availableBalance.toString())) {
                        return locale.insufficientWalletBalance;
                      }
                      return null;
                    },
                  ),
                  16.height,
                  Row(
                    children: [
                      Text(locale.chooseBank, style: primaryTextStyle(size: 12, weight: FontWeight.w600)),
                      Spacer(),
                      TextButton(
                        onPressed: () {
                          AddBankScreen(
                            title: locale.addBank,
                          ).launch(context).then((value) {
                            if (value.isNotEmpty) {
                              if (value[0]) {
                                init(value[1]);
                                setState(() {});
                              }
                            }
                          });
                        },
                        child: Text(locale.addBank, style: boldTextStyle(size: 12, color: primaryColor)),
                      ),
                    ],
                  ),
                  8.height,
                  DropdownButtonFormField<BankHistory>(
                    decoration: inputDecoration(context),
                    isExpanded: true,
                    menuMaxHeight: 300,
                    value: selectedBank,
                    hint: Text(
                      locale.egCentralNationalBank,
                      style: secondaryTextStyle(size: 12),
                    ),
                    icon: Icon(Icons.keyboard_arrow_down_sharp),
                    dropdownColor: context.cardColor,
                    items: bankHistoryList.where((e) => e.status != 1).map((BankHistory e) {
                      return DropdownMenuItem<BankHistory>(
                        value: e,
                        child: Text(e.bankName.validate(), style: primaryTextStyle(), maxLines: 1, overflow: TextOverflow.ellipsis),
                      );
                    }).toList(),
                    onChanged: (BankHistory? value) async {
                      selectedBank = value;
                      setState(() {});
                    },
                    validator: (value) {
                      if (value == null) return errorThisFieldRequired;
                      return null;
                    },
                  ),
                  40.height,
                  AppButton(
                    text: locale.withdraw,
                    height: 40,
                    color: primaryColor,
                    textStyle: boldTextStyle(color: white),
                    width: context.width() - context.navigationBarHeight,
                    onTap: () {
                      if (formKey.currentState!.validate()) {
                        withdrawMoney();
                      }
                    },
                  ),
                ],
              ).paddingSymmetric(horizontal: 16, vertical: 16),
            ),
            Observer(builder: (_) => LoaderWidget().center().visible(appStore.isLoading)),
          ],
        ),
      ),
    );
  }
}