import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:modal_progress_hud_nsn/modal_progress_hud_nsn.dart';
import 'package:road24_mobile/data/repository/CardRepository.dart';
import 'package:road24_mobile/model/blocs/payment/payment_bloc.dart';
import 'package:road24_mobile/model/utils/Config.dart';
import 'package:road24_mobile/model/utils/styles/AppColors.dart';
import 'package:road24_mobile/model/utils/styles/AppStyles.dart';
import 'package:road24_mobile/my_app.dart';
import 'package:road24_mobile/view/built/i18n.dart';
import 'package:road24_mobile/view/home/dash_board.dart';
import 'package:road24_mobile/view/mycar/fines/fine_details_page.dart';
import 'package:road24_mobile/view/mycar/fines/payment/payment_verify_page.dart';
import 'package:road24_mobile/view/settings/card/cards_page.dart';
import 'package:road24_mobile/view/widgets/custom_bottom_tabbar.dart';
import 'package:road24_mobile/view/widgets/custom_button.dart';
import 'package:road24_mobile/view/widgets/fade_route.dart';
import 'package:road24_mobile/view/widgets/no_connection_screen.dart';
import 'package:road24_mobile/view/widgets/success_page.dart';
import 'package:road24_mobile/view/widgets/items/card_bottom_sheet_item.dart';
import 'package:road24_mobile/utils/extensions.dart';

import 'package:road24_mobile/utils/frequent_widgets.dart';

class PayForm extends StatefulWidget {
  final int cardId;
  final String fineToShow;
  final String remain;

  const PayForm(
      {Key? key,
      required this.cardId,
      required this.remain,
      required this.fineToShow})
      : super(key: key);

  @override
  _PayFormState createState() => _PayFormState();
}

class _PayFormState extends State<PayForm> {
  late PaymentBloc paymentBloc;
  late TextEditingController sumController;
  late ValueNotifier<String> sumNotifier;
  bool loading = false;
  bool _isSnackBarActive = false;
  late bool verified;
  GlobalKey<ScaffoldState> _key = GlobalKey();
  int minPaymentSum = 1000;
  bool validForMinimality = false;

  bool isValidNumber = true;

  @override
  void initState() {
    super.initState();
    paymentBloc = PaymentBloc(repository: CardRepository());
    sumController = TextEditingController()
      ..addListener(() {
        try {
          checkSum(int.parse(sumController.text));
        } catch (e) {
          print("can't parse");
        }
        sumNotifier.value = sumController.text;
      });
    sumNotifier = ValueNotifier('');
  }

  String humanizeCost(String sum) {
    if (sum.endsWith('.0')) {
      sum = sum + '0';
    }
    List<String> sumBuffer = sum.split('.');
    String refactoredSumFormat =
        FrequentWidgets.intComma(int.parse(sumBuffer[0])).replaceAll(',', ' ') +
            '.' +
            sumBuffer[1].toString();
    refactoredSumFormat = refactoredSumFormat.replaceAll(".00", "");
    return refactoredSumFormat;
  }

  @override
  void dispose() {
    sumController.dispose();
    sumNotifier.dispose();
    paymentBloc.close();
    super.dispose();
  }

  checkSum(int sum) {
    setState(() {
      int? remain;
      try {
        remain = int.parse(humanizeCost(widget.remain).replaceAll(' ', ''));
      } catch (e) {}
      if (remain != null) {
        if (remain - sum != 0 &&
            remain - sum > 0 &&
            remain - sum < minPaymentSum) {
          isValidNumber = false;
        } else
          isValidNumber = true;

        if (remain < minPaymentSum) {
          if (sum == remain) {
            validForMinimality = true;
          } else {
            validForMinimality = false;
          }
        } else {
          if (sum >= minPaymentSum) {
            validForMinimality = true;
          } else {
            validForMinimality = false;
          }
        }
      }
    });
  }

  @override
  Widget build(BuildContext context) {
    return ValueListenableBuilder(
      valueListenable: MyApp.hasInternet,
      builder: (context, bool hasInternet, _) {
        return (hasInternet)
            ? ModalProgressHUD(
                inAsyncCall: loading,
                color: AppColors.unSelectedColor,
                progressIndicator: CircularProgressIndicator(
                  strokeWidth: 3.0,
                  valueColor: AlwaysStoppedAnimation<Color>(
                    AppColors.unSelectedColor,
                  ),
                ),
                child: GestureDetector(
                  onTap: () {
                    FocusScope.of(context).requestFocus(new FocusNode());
                  },
                  child: Scaffold(
                    appBar: AppBar(
                      toolbarHeight: 60.0,
                      leading: FrequentWidgets.appBarBackButton(context),
                    ),
                    key: _key,
                    backgroundColor: Color(0xffF9F9F9),
                    body: SafeArea(
                      child: BlocListener(
                        bloc: paymentBloc,
                        listener: (context, state) {
                          if (state is PaymentRequestAccepted) {
                            if (int.parse(sumController.text) >= 50000) {
                              Navigator.pushReplacement(
                                  context,
                                  CupertinoPageRoute(
                                      builder: (context) => PaymentVerifyPage(
                                          cardId: widget.cardId,
                                          fineId:
                                              FineDetailsPage.currentFineId!,
                                          amount: sumController.text)));
                            } else {
                              DashBoard.activeTab.value =
                                  CustomBottomTabBar.indexMap['MyAvto'] ?? 0;
                              Navigator.pushReplacement(
                                  context,
                                  MaterialPageRoute(
                                    builder: (context) => SuccessPage(
                                      text:
                                          S.of(context).payment_request_success,
                                      subText: S
                                          .of(context)
                                          .payment_request_success_description,
                                      onTap: () {
                                        Navigator.pushAndRemoveUntil(
                                          context,
                                          FadeRoute(page: DashBoard()),
                                          (route) => false,
                                        );
                                      },
                                      fromFinePaying: true,
                                    ),
                                  ));
                            }
                          }
                          if (state is PaymentError) {
                            setState(() {
                              loading = false;
                            });
                            if (!_isSnackBarActive) {
                              _isSnackBarActive = true;

                              String text = "";
                              try {
                                text =
                                    state.exception.toString().getErrorText();
                              } catch (ex) {
                                text = state.exception.toString();
                              }

                              Config.showSnackBar(
                                context,
                                text,
                              );
                              // }
                            }
                            Future.delayed(Duration(milliseconds: 3000))
                                .then((value) {
                              if (mounted)
                                setState(() => _isSnackBarActive = false);
                            });
                          }
                          // }
                        },
                        child: BlocBuilder(
                          bloc: paymentBloc,
                          builder: (context, state) => SingleChildScrollView(
                            child: Column(
                              mainAxisAlignment: MainAxisAlignment.start,
                              crossAxisAlignment: CrossAxisAlignment.start,
                              children: [
                                SizedBox(height: 11.0),
                                Padding(
                                  padding:
                                      EdgeInsets.symmetric(horizontal: 15.0),
                                  child: Text(
                                    S.of(context).decree_number.toUpperCase(),
                                    style: AppStyle.textStyle().copyWith(
                                        color: Color(0xff282828),
                                        fontWeight: FontWeight.w600,
                                        fontSize: 16.0),
                                    maxLines: 1,
                                    overflow: TextOverflow.ellipsis,
                                  ),
                                ),
                                Padding(
                                  padding:
                                      EdgeInsets.symmetric(horizontal: 15.0),
                                  child: Text(
                                    widget.fineToShow,
                                    style: AppStyle.textStyle().copyWith(
                                        color: Color(0xff282828),
                                        fontWeight: FontWeight.w600,
                                        fontSize: 20.0),
                                    maxLines: null,
                                    overflow: TextOverflow.ellipsis,
                                  ),
                                ),
                                SizedBox(height: 20.0),
                                Padding(
                                  padding:
                                      EdgeInsets.symmetric(horizontal: 15.0),
                                  child: Text(
                                    S.of(context).card_number.toUpperCase(),
                                    style: AppStyle.textStyle().copyWith(
                                        color: Color(0xff282828),
                                        fontWeight: FontWeight.w600,
                                        fontSize: 16.0),
                                    maxLines: 1,
                                    overflow: TextOverflow.ellipsis,
                                  ),
                                ),
                                Padding(
                                  padding:
                                      EdgeInsets.symmetric(horizontal: 15.0),
                                  child: Row(
                                    children: [
                                      Expanded(
                                        flex: 2,
                                        child: Text(
                                          '${CardsPage.cards[CardBottomSheetItem.currentCard].number.substring(0, 4)} ${CardsPage.cards[CardBottomSheetItem.currentCard].number.substring(4, 6)}••  ••••  ${CardsPage.cards[CardBottomSheetItem.currentCard].number.substring(12, 16)}',
                                          textAlign: TextAlign.start,
                                          style: AppStyle.textStyle().copyWith(
                                              color: Color(0xff282828),
                                              fontWeight: FontWeight.w600,
                                              fontSize: 20.0),
                                          maxLines: null,
                                          overflow: TextOverflow.ellipsis,
                                        ),
                                      ),
                                      // Expanded(flex: 1, child: Container(padding: EdgeInsets.symmetric(horizontal: 10.0), color: Colors.black, child: CardsPage.banksLogos[CardsPage.cards[CardBottomSheetItem.currentCard].number.substring(0, 6)]??CardsPage.banksLogos[CardsPage.cards[CardBottomSheetItem.currentCard].number.substring(0, 2)]))
                                    ],
                                  ),
                                ),
                                SizedBox(height: 20.0),
                                Padding(
                                  padding:
                                      EdgeInsets.symmetric(horizontal: 15.0),
                                  child: Text(
                                    (S.of(context).remain +
                                            ' (' +
                                            S.of(context).uzs +
                                            ')')
                                        .toUpperCase(),
                                    style: AppStyle.textStyle().copyWith(
                                        color: Color(0xff282828),
                                        fontWeight: FontWeight.w600,
                                        fontSize: 16.0),
                                    maxLines: 1,
                                    overflow: TextOverflow.ellipsis,
                                  ),
                                ),
                                Padding(
                                  padding:
                                      EdgeInsets.symmetric(horizontal: 15.0),
                                  child: Text(
                                    humanizeCost(widget.remain),
                                    style: AppStyle.textStyle().copyWith(
                                        color: Color(0xffF51A51),
                                        fontWeight: FontWeight.w600,
                                        fontSize: 20.0),
                                    maxLines: null,
                                    overflow: TextOverflow.ellipsis,
                                  ),
                                ),
                                // ),
                                SizedBox(height: 20.0),
                                Padding(
                                  padding: EdgeInsets.symmetric(
                                      horizontal: 16.0, vertical: 7.0),
                                  child: Row(
                                    // mainAxisAlignment: MainAxisAlignment.center,
                                    mainAxisSize: MainAxisSize.min,
                                    crossAxisAlignment:
                                        CrossAxisAlignment.start,
                                    children: [
                                      Expanded(
                                        flex: 5,
                                        child: TextFormField(
                                          cursorColor: AppColors.selectedColor,
                                          controller: sumController,
                                          maxLines: 1,
                                          maxLength: 7,
                                          buildCounter: (
                                            context, {
                                            required int currentLength,
                                            required bool isFocused,
                                            maxLength,
                                          }) =>
                                              null,
                                          keyboardType:
                                              TextInputType.numberWithOptions(
                                                  decimal: true),
                                          inputFormatters: [
                                            FilteringTextInputFormatter.allow(
                                                RegExp(r"^[1-9]{1}[0-9]*$")),
                                            TextInputFormatter.withFunction(
                                                (oldValue, newValue) {
                                              try {
                                                final text = newValue.text;
                                                if (text.isNotEmpty)
                                                  double.parse(text);
                                                return newValue;
                                              } catch (e) {}
                                              return oldValue;
                                            }),
                                          ],
                                          textCapitalization:
                                              TextCapitalization.sentences,
                                          textAlign: TextAlign.left,
                                          style: AppStyle.textStyle().copyWith(
                                            color: Color(0xff282828),
                                            fontSize: 17.0,
                                            fontWeight: FontWeight.normal,
                                          ),
                                          decoration: InputDecoration(
                                            errorText: isValidNumber
                                                ? null
                                                : S.of(context).less_amount,
                                            errorMaxLines: 2,
                                            hintText:
                                                "${S.of(context).enter_sum}",
                                            hintStyle:
                                                AppStyle.textStyle().copyWith(
                                              color: AppColors.unSelectedColor,
                                              fontSize: 17.0,
                                              fontWeight: FontWeight.normal,
                                            ),
                                            border: OutlineInputBorder(
                                              borderRadius:
                                                  BorderRadius.circular(12.0),
                                              borderSide: BorderSide(
                                                  color: Colors.transparent),
                                            ),
                                            enabledBorder: OutlineInputBorder(
                                              borderRadius:
                                                  BorderRadius.circular(12.0),
                                              borderSide: BorderSide(
                                                  color: Color(0xFFE0E0E0),
                                                  width: 1.0),
                                            ),
                                            fillColor: Color(0xffEFEFEF),
                                            filled: true,
                                            focusedBorder: OutlineInputBorder(
                                              borderRadius:
                                                  BorderRadius.circular(12.0),
                                              borderSide: BorderSide(
                                                  color: Colors.black,
                                                  width: 1.5),
                                            ),
                                            contentPadding:
                                                EdgeInsets.all(15.0),
                                          ),
                                        ),
                                      ),
                                      SizedBox(width: 4.0),
                                      Expanded(
                                        flex: 2,
                                        child: OutlinedButton(
                                          style: OutlinedButton.styleFrom(
                                            shape: RoundedRectangleBorder(
                                                borderRadius:
                                                    BorderRadius.circular(
                                                        12.0)),
                                          ),
                                          onPressed: () {
                                            sumController.text =
                                                humanizeCost(widget.remain)
                                                    .replaceAll(" ", "");
                                            sumController.selection =
                                                TextSelection.collapsed(
                                                    offset: sumController
                                                        .text.length);
                                          },
                                          child: Container(
                                            height: 55.0,
                                            child: Center(
                                              child: Text(
                                                S.of(context).all_for_pay,
                                                maxLines: 2,
                                                style: AppStyle.textStyle()
                                                    .copyWith(
                                                        color:
                                                            Color(0xff282828),
                                                        fontSize: 15.0),
                                              ),
                                            ),
                                          ),
                                        ),
                                      ),
                                    ],
                                  ),
                                ),
                                ValueListenableBuilder(
                                  valueListenable: sumNotifier,
                                  builder: (context, String notifier, _) =>
                                      Padding(
                                    padding: EdgeInsets.symmetric(
                                        horizontal: 15.0, vertical: 10.0),
                                    child: IgnorePointer(
                                      ignoring: !(notifier.isNotEmpty &&
                                          validForMinimality &&
                                          isValidNumber &&
                                          _isSnackBarActive == false),
                                      child: CustomButton(
                                        onTap: () {
                                          if (_isSnackBarActive ||
                                              !isValidNumber) {
                                            return;
                                          }
                                          if (!loading) {
                                            late int remain;
                                            try {
                                              remain = int.parse(
                                                  humanizeCost(widget.remain)
                                                      .replaceAll(' ', ''));
                                            } catch (e) {}
                                            if (remain <
                                                int.parse(sumController.text)) {
                                              Config.showSnackBar(
                                                context,
                                                S.of(context).over_amount,
                                              );
                                            } else {
                                              setState(() => loading = true);
                                              paymentBloc.add(
                                                PayFine(
                                                  cardId: widget.cardId,
                                                  sum: double.tryParse(
                                                      notifier)!,
                                                  fineId: FineDetailsPage
                                                      .currentFineId!,
                                                ),
                                              );
                                            }
                                          }
                                        },
                                        color: (notifier.isNotEmpty &&
                                                validForMinimality &&
                                                _isSnackBarActive == false)
                                            ? AppColors.selectedColor
                                            : AppColors.unSelectedColor,
                                        title: S.of(context).pay,
                                      ),
                                    ),
                                  ),
                                ),
                                Center(
                                  child: Padding(
                                    padding: EdgeInsets.symmetric(
                                        horizontal: 15.0, vertical: 5.0),
                                    child: Text(
                                      S
                                          .of(context)
                                          .card_one_percent_notification,
                                      style: AppStyle.textStyle().copyWith(
                                          color: Color(0xffF51A51),
                                          fontWeight: FontWeight.w600,
                                          fontSize: 15.0),
                                      maxLines: 3,
                                      overflow: TextOverflow.ellipsis,
                                    ),
                                  ),
                                )
                                // : SizedBox(),
                                // ),
                              ],
                            ),
                          ),
                        ),
                      ),
                    ),
                  ),
                ),
              )
            : NoConnectionScreen(
                onTap: () {
                  Navigator.pop(context);
                  Navigator.pop(context);
                },
              );
      },
    );
  }
}
