import 'dart:async';

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/card/card_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/check_internet.dart';
import 'package:road24_mobile/view/built/i18n.dart';
import 'package:road24_mobile/view/mycar/my_car_page.dart';
import 'package:road24_mobile/view/mycar/fines/fine_details_page.dart';
import 'package:road24_mobile/view/mycar/fines/fines_page.dart';
import 'package:road24_mobile/view/settings/card/cards_page.dart';
import 'package:road24_mobile/view/widgets/fade_route.dart';
import 'package:road24_mobile/view/widgets/items/card_bottom_sheet_item.dart';
import 'package:road24_mobile/utils/extensions.dart';
import 'package:road24_mobile/view/widgets/no_connection_screen.dart';
import 'package:sizer/sizer.dart';
import 'package:sms_autofill/sms_autofill.dart';

import '../../../../my_app.dart';

class SmsVerificationForCardPage extends StatefulWidget {
  final int cardId;
  final bool isResendSmsCode;
  const SmsVerificationForCardPage(
      {Key? key, required this.cardId, this.isResendSmsCode = false})
      : super(key: key);

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

class _SmsVerificationForCardPageState extends State<SmsVerificationForCardPage>
    with CodeAutoFill {
  var smsCode = TextEditingController();
  CardBloc cardBlocToVerifyProcess = CardBloc(repository: CardRepository());
  int limit = 60;
  bool loading = false;
  bool _isSnackBarActive = false;
  bool verified = false;
  late ValueNotifier<int>? timeLeftInSeconds;
  GlobalKey<ScaffoldState> _key = GlobalKey();
  Timer? _timer;
  bool isStopped = false;

  @override
  void codeUpdated() {
    if (code != null && mounted)
      setState(() {
        smsCode.text = code!;
      });
  }

  @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) {}
        }
      });
    if (widget.isResendSmsCode) {
      cardBlocToVerifyProcess.add(ResendVerificationCodeEvent(widget.cardId));
    } else
      startTimer();
    // countdown();

    listenForCode();

    SmsAutoFill()
        .getAppSignature
        .then((value) => print("signature card...$value"));

    smsCode.addListener(() {
      if (smsCode.text.toString().isEmpty) return;
      if (smsCode.text.toString().length == 6) {
        if (!verified) {
          cardBlocToVerifyProcess
              .add(VerifyCardEvent(widget.cardId, smsCode.text));
        }
      }
    });
  }

  @override
  void dispose() {
    // if (!verified) {
    //   CardRepository().deleteCard(widget.cardId);
    // }

    if (timeLeftInSeconds != null) timeLeftInSeconds?.dispose();
    smsCode.dispose();
    cardBlocToVerifyProcess.close();
    if (_timer != null) {
      print("timer disposed in card");
      _timer!.cancel();
    }
    try {
      SmsAutoFill().unregisterListener();
    } catch (_) {}
    cancel();
    super.dispose();
  }

  void startTimer() {
    print("timer started");
    const oneSec = const Duration(seconds: 1);
    if (_timer != null) _timer!.cancel();
    _timer = Timer.periodic(oneSec, (Timer timer) {
      if (isStopped)
        _timer?.cancel();
      else if (timeLeftInSeconds!.value < 1) {
        timer.cancel();
      } else {
        timeLeftInSeconds!.value--;
      }
    });
  }

  checkInternet() async {
    setState(() {
      loading = true;
    });
    if (await CheckInternet.isInternet()) {
      MyApp.hasInternet.value = true;
    }
    setState(() {
      loading = false;
    });
  }

  @override
  Widget build(BuildContext context) {
    return ValueListenableBuilder<bool>(
        valueListenable: MyApp.hasInternet,
        builder: (context, 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: Material(
                          type: MaterialType.transparency,
                          child: InkWell(
                            onTap: () {
                              Navigator.pop(context);
                            },
                            child: Container(
                              margin: EdgeInsets.all(10.0),
                              decoration: BoxDecoration(
                                color: Color(0xffDFDFDF),
                                shape: BoxShape.circle,
                              ),
                              child: Center(
                                child: Icon(
                                  Icons.arrow_back_ios_outlined,
                                  size: 20.0,
                                  color: Colors.black,
                                ),
                              ),
                            ),
                          ),
                        ),
                      ),
                      key: _key,
                      backgroundColor: Color(0xffF9F9F9),
                      body: SafeArea(
                        child: BlocListener(
                          bloc: cardBlocToVerifyProcess,
                          listener: (context, state) {
                            // setState(() {
                            //   isStopped = true;
                            // });
                            if (state is VerificationCodeResent) {
                              startTimer();
                            }
                            if (state is CardIsVerifiedSuccessState) {
                              verified = true;
                              if (CardBottomSheetItem.fromFineDetailPage) {
                                if (MyCarPage.current != null) {
                                  Navigator.pushAndRemoveUntil(
                                      context,
                                      FadeRoute(page: FinesPage()),
                                      (route) => route.isFirst);
                                  Navigator.push(
                                      context,
                                      FadeRoute(
                                          page: FineDetailsPage(
                                        id: FineDetailsPage.currentFineId!,
                                      )));
                                  FineDetailsPage.currentFineId = null;
                                } else {
                                  Navigator.pushAndRemoveUntil(
                                      context,
                                      FadeRoute(
                                          page: FineDetailsPage(
                                        id: FineDetailsPage.currentFineId!,
                                      )),
                                      (route) => route.isFirst);
                                  FineDetailsPage.currentFineId = null;
                                }
                              } else {
                                print("from here");
                                Navigator.pop(context, true);
                                CardsPage.needToRefresh.value = true;
                              }
                            }
                            if (state is CardLoadingError) {
                              if (!_isSnackBarActive) {
                                _isSnackBarActive = true;
                                // try {
                                //   Config.showSnackBar(context,
                                //       json
                                //           .decode(
                                //               ApiException.errorMessage.value.toString())
                                //           .values
                                //           .first
                                //           .first
                                //           .toString(),
                                //       _key);
                                // } catch (e) {
                                //   try {
                                //     Config.showSnackBar(context,
                                //         json
                                //             .decode(
                                //                 ApiException.errorMessage.value.toString())
                                //             .values
                                //             .first
                                //             .toString(),
                                //         _key);
                                //   } catch (e) {
                                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 if (left == 0)
                                        return Align(
                                          alignment: Alignment.centerRight,
                                          child: InkWell(
                                            onTap: () async {
                                              cardBlocToVerifyProcess.add(
                                                  ResendVerificationCodeEvent(
                                                      widget.cardId));
                                              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),
                                              ),
                                            ),
                                          ),
                                        );

                                      return Container();
                                    }),
                              ],
                            ),
                          ),
                        ),
                      ),
                    ),
                  ),
                )
              : NoConnectionScreen(onTap: () async {
                  await checkInternet();
                });
        });
  }
}
