import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:mask_text_input_formatter/mask_text_input_formatter.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/utils/frequent_widgets.dart';
import 'package:road24_mobile/view/built/i18n.dart';
import 'package:road24_mobile/view/home/dash_board.dart';
import 'package:road24_mobile/view/widgets/custom_bottom_tabbar.dart';
import 'package:road24_mobile/view/widgets/fade_route.dart';
import 'package:road24_mobile/utils/extensions.dart';
import 'package:road24_mobile/view/widgets/success_page.dart';
import 'package:sizer/sizer.dart';
import 'package:sms_autofill/sms_autofill.dart';

class PaymentVerifyPage extends StatefulWidget {
  final int cardId;
  final int fineId;
  final String amount;
  const PaymentVerifyPage({
    Key? key,
    required this.cardId,
    required this.fineId,
    required this.amount,
  }) : super(key: key);

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

class _PaymentVerifyPageState extends State<PaymentVerifyPage> {
  var smsCode = TextEditingController();
  var _paymentBloc = PaymentBloc(repository: CardRepository());
  int limit = 60;
  bool loading = false;
  bool _isSnackBarActive = false;
  late ValueNotifier<int> timeLeftInSeconds;
  GlobalKey<ScaffoldState> _key = GlobalKey();
  // bool isInitial = true;
  bool isSendAgain = false;
  bool payed = false;
  @override
  void initState() {
    super.initState();
    timeLeftInSeconds = ValueNotifier(limit)
      ..addListener(() {
        if (timeLeftInSeconds.value == 0) {
          try {
            Config.showSnackBar(context, S.of(context).time_exceeded,
                isRed: true);
          } catch (e) {}
        }
      });
    countdown();
    try {
      SmsAutoFill().code.listen((event) {
        smsCode.text = event;
      });
    } catch (_) {}
    smsCode.addListener(() {
      if (smsCode.text.toString().isEmpty) return;
      if (smsCode.text.toString().length == 6 && !payed) {
        if (mounted)
          setState(() {
            loading = true;
            payed = true;
          });
        _paymentBloc.add(PayFine(
            cardId: widget.cardId,
            sum: double.parse(widget.amount),
            fineId: widget.fineId,
            smsCode: smsCode.text.trim()));
      }
    });
  }

  @override
  void dispose() {
    _paymentBloc.close();
    smsCode.dispose();
    if (timeLeftInSeconds != null) timeLeftInSeconds.dispose();
    try {
      SmsAutoFill().unregisterListener();
    } catch (_) {}
    super.dispose();
  }

  void countdown() async {
    for (int i = 0; i < limit; i++) {
      try {
        await Future.delayed(Duration(seconds: 1));
        await SmsAutoFill().listenForCode();
        timeLeftInSeconds.value--;
      } catch (e) {}
    }
  }

  @override
  Widget build(BuildContext context) {
    return 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) {
                  print("payment request state");
                  if (mounted)
                    setState(() {
                      loading = false;
                    });
                  // if (isInitial) {
                  //   setState(() {
                  //     isInitial = false;
                  //   });
                  //   countdown();
                  // } else
                  if (isSendAgain) {
                    if (mounted)
                      setState(() {
                        isSendAgain = false;
                      });

                    timeLeftInSeconds.value = 60;
                    countdown();
                  } 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) {
                  if (mounted)
                    setState(() {
                      loading = false;
                      smsCode.clear();
                      payed = false;
                    });

                  if (!_isSnackBarActive) {
                    _isSnackBarActive = true;

                    String text = "";
                    try {
                      text = state.exception.toString().getErrorText();
                    } catch (ex) {
                      text = state.exception.toString();
                    }
                    Config.showSnackBar(context, text);
                  }
                  _isSnackBarActive = false;
                }
              },
              child: SingleChildScrollView(
                child: Column(
                  mainAxisAlignment: MainAxisAlignment.start,
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    SizedBox(height: 11.0),
                    Padding(
                      padding: EdgeInsets.symmetric(horizontal: 16.0),
                      child: Text(
                        "${S.of(context).number_from_sms}",
                        style: AppStyle.textStyle().copyWith(
                            color: Color(0xFF959595),
                            fontWeight: FontWeight.normal,
                            fontSize: 14.0),
                      ),
                    ),
                    Padding(
                      padding:
                          EdgeInsets.symmetric(horizontal: 16.0, vertical: 7.0),
                      child: Stack(
                        children: [
                          TextFormField(
                            cursorColor: AppColors.selectedColor,
                            maxLines: 1,
                            inputFormatters: [
                              MaskTextInputFormatter(
                                mask: '######',
                              ),
                            ],
                            autofocus: true,
                            keyboardType: TextInputType.number,
                            textCapitalization: TextCapitalization.sentences,
                            controller: smsCode,
                            textAlign: TextAlign.left,
                            style: AppStyle.textStyle().copyWith(
                              color: Color(0xff282828),
                              fontSize: 17.0,
                              fontWeight: FontWeight.normal,
                            ),
                            decoration: InputDecoration(
                              hintText: "${S.of(context).enter_sms_code}",
                              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),
                            ),
                            // validator: (value) {
                            //   if (value!.isEmpty) {
                            //     return S.of(context).validationForEmpty;
                            //   } else {
                            //     if (value.replaceAll(" ", "").length == 16) {
                            //       return null;
                            //     } else {
                            //       return S
                            //           .of(context)
                            //           .validationForMinimumNumber(16);
                            //     }
                            //   }
                            // },
                          ),
                          Align(
                            alignment: Alignment.centerRight,
                            child: Container(
                              width: 50.0,
                              height: 50.0,
                              margin: EdgeInsets.symmetric(horizontal: 10.0),
                              child: Center(
                                child: ValueListenableBuilder(
                                  valueListenable: timeLeftInSeconds,
                                  builder: (context, int left, _) {
                                    print(left);
                                    int minutes = left ~/ 60;
                                    int seconds = left % 60;
                                    String minutesToShow;
                                    String secondsToShow;
                                    if (minutes < 10) {
                                      minutesToShow = '0$minutes';
                                    } else {
                                      minutesToShow = minutes.toString();
                                    }
                                    if (seconds < 10) {
                                      secondsToShow = '0$seconds';
                                    } else {
                                      secondsToShow = seconds.toString();
                                    }
                                    return Container(
                                      width: 100.0,
                                      child: Text(
                                        '$minutesToShow:$secondsToShow',
                                      ),
                                    );
                                  },
                                ),
                              ),
                            ),
                          ),
                        ],
                      ),
                    ),
                    ValueListenableBuilder(
                      valueListenable: timeLeftInSeconds,
                      builder: (context, int left, _) {
                        if (left > 0) {
                          return Padding(
                            padding: EdgeInsets.symmetric(horizontal: 5.0.w),
                            child: Text(
                              "${S.of(context).card_verification}",
                              style: AppStyle.textStyle().copyWith(
                                  color: Color(0xff747474),
                                  fontWeight: FontWeight.w400,
                                  fontSize: 15.0),
                            ),
                          );
                        } else {
                          return Row(
                            mainAxisAlignment: MainAxisAlignment.end,
                            children: [
                              (left == 0)
                                  ? InkWell(
                                      onTap: () async {
                                        setState(() {
                                          isSendAgain = true;
                                          loading = true;
                                        });
                                        _paymentBloc.add(PayFine(
                                            cardId: widget.cardId,
                                            sum: double.parse(widget.amount),
                                            fineId: widget.fineId));
                                        // timeLeftInSeconds.value = 60;
                                        // countdown();
                                      },
                                      child: Padding(
                                        padding: EdgeInsets.symmetric(
                                            vertical: 4.0, horizontal: 16.0),
                                        child: Text(
                                          "${S.of(context).send_again.toLowerCase()}",
                                          style: AppStyle.textStyle().copyWith(
                                              color: Color(0xff5556E8),
                                              fontWeight: FontWeight.w500,
                                              fontSize: 16.0),
                                        ),
                                      ),
                                    )
                                  : SizedBox(),
                            ],
                          );
                        }
                      },
                    ),
                  ],
                ),
              ),
            ),
          ),
        ),
      ),
    );
  }
}
