import 'dart:async';

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/http/ApiException.dart';
import 'package:road24_mobile/data/repository/CarsRepository.dart';
import 'package:road24_mobile/data/repository/UserRepository.dart';
import 'package:road24_mobile/data/response/CarsResponse.dart';
import 'package:road24_mobile/model/blocs/auth/auth_bloc.dart';
import 'package:road24_mobile/model/blocs/mycar/cars_bloc.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/settings/rocket_chat.dart';
import 'package:road24_mobile/view/widgets/custom_bottom_tabbar.dart';
import 'package:road24_mobile/view/widgets/no_connection_screen.dart';
import 'package:road24_mobile/view/widgets/text_field_custom_formatter.dart';
import 'package:road24_mobile/utils/extensions.dart';
import 'package:sizer/sizer.dart';
import 'package:sms_autofill/sms_autofill.dart';
import '../firebase.dart';
import 'auth_success_page.dart';

class SmsVerificationPage extends StatefulWidget {
  final String phoneNumber;

  const SmsVerificationPage({Key? key, required this.phoneNumber})
      : super(key: key);

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

class _SearchAddressPageState extends State<SmsVerificationPage>
    with CodeAutoFill {
  final AuthBloc _bloc = AuthBloc(repository: UserRepository());
  final TextEditingController smsCode = TextEditingController();
  final GlobalKey<ScaffoldState> _key = GlobalKey();
  int limit = 60;
  ValueNotifier<int>? timeLeftInSeconds = ValueNotifier(60);
  bool loading = true;
  bool eventSent = false;
  late CarsBloc carsBloc;

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

  @override
  void initState() {
    super.initState();
    try {
      listenForCode();
    } catch (e) {
      print("exception in listening sms code...$e");
    }
    FirebaseNotifications.requestNotificationPermission();

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

    MyApp.preferences?.setPhoneNUmber(widget.phoneNumber);
    // timeLeftInSeconds = ValueNotifier(limit);

    _bloc.add(SMSSendingEvent(phone: widget.phoneNumber));

    carsBloc = CarsBloc(repository: CarsRepository());

    smsCode.addListener(() {
      if (smsCode.text.toString().isEmpty) return;
      if (smsCode.text.toString().length == 6) {
        if (!eventSent) {
          setState(() {
            loading = true;
            // smsOTP = smsCode.text.toString();
          });
          _bloc.add(SMSVerificationEvent(
              widget.phoneNumber, smsCode.text.toString()));
          eventSent = true;
        }
      }
    });
    print("Phone Number ${widget.phoneNumber}");
  }

  Timer? _timer;
  bool isStopped = false;

  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
        setState(
          () {
            if (timeLeftInSeconds!.value < 1) {
              timer.cancel();
            } else {
              timeLeftInSeconds!.value--;
            }
          },
        );
    });
  }

  @override
  void dispose() {
    if (timeLeftInSeconds != null) timeLeftInSeconds?.dispose();
    smsCode.dispose();
    _bloc.close();
    carsBloc.close();
    if (_timer != null) {
      print("timer disposed");
      _timer!.cancel();
    }
    SmsAutoFill().unregisterListener();
    cancel();
    super.dispose();
  }

  void showError(dynamic error) {
    String errorText = "";
    try {
      errorText = "$error".toString().getErrorText();
    } catch (ex) {
      errorText = error.toString();
    }
    var bar = SnackBar(
      content: Text(errorText),
      // ? "${S.of(context).try_again_sms}"
      // "$error".replaceAll("Exception:", "")),
      // content: Text(error.value.toString()),
      duration: const Duration(milliseconds: 3000),
      backgroundColor: AppColors.selectedColor,
    );
    ScaffoldMessenger.of(context).showSnackBar(bar);
  }

  @override
  Widget build(BuildContext context) {
    // print("there");
    // print(MyApp.sharedPreferences.get(Config.userRefreshTokenKey));
    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: Scaffold(
                  key: _key,
                  backgroundColor: Color(0xffF9F9F9),
                  body: SafeArea(
                    child: GestureDetector(
                      onTap: () {
                        FocusScope.of(context).requestFocus(new FocusNode());
                      },
                      child: BlocListener(
                        bloc: carsBloc,
                        listener: (context, state) {
                          setState(() {
                            isStopped = true;
                          });
                          if (state is CarListSuccessState) {
                            List<Results> list = state.response.results;

                            if (list.isNotEmpty) {
                              DashBoard.activeTab.value =
                                  CustomBottomTabBar.indexMap['MyAvto'];

                              Navigator.pushAndRemoveUntil(
                                context,
                                CupertinoPageRoute(builder: (_) => DashBoard()),
                                (route) => false,
                              );
                            } else {
                              Navigator.pushAndRemoveUntil(
                                context,
                                CupertinoPageRoute(
                                    builder: (_) => AuthSuccessPage()),
                                (route) => false,
                              );
                            }
                          } else if (state is CarsLoadingError) {
                            Navigator.pushAndRemoveUntil(
                              context,
                              CupertinoPageRoute(builder: (_) => DashBoard()),
                              (route) => false,
                            );
                          }
                        },
                        child: BlocListener(
                          bloc: _bloc,
                          listener: (context, state) async {
                            if (state is AuthSMSSentSuccessState) {
                              setState(() {
                                loading = false;
                              });
                              startTimer();
                            }
                            if (state is AuthLoadingError) {
                              setState(() {
                                loading = false;
                              });
                              showError(ApiException.errorMessage.value);
                              eventSent = false;

                              startTimer();
                            }
                            if (state is SMSVerifiedSuccessState) {
                              setState(() {
                                loading = false;
                                if (_timer != null) _timer!.cancel();
                              });
                              MyApp.preferences
                                  ?.setToken(state.response.access);
                              MyApp.preferences
                                  ?.setRefreshToken(state.response.refresh);
                              MyApp.preferences
                                  ?.setPhoneNUmber(widget.phoneNumber);

                              FirebaseNotifications().setUpFirebase(context);
                              /*uncomment if you need to get full username*/

                              // final dynamic response =
                              //     await UserRepository().getUser();
                              // UserResponse userResponse =
                              //     UserResponse.fromJson(response);
                              // if (userResponse.firstName.length > 0) {
                              // DashBoard.activeTab.value =
                              //     CustomBottomTabBar.indexMap['MyAvto'];

                              // Navigator.pushAndRemoveUntil(
                              //   context,
                              //   CupertinoPageRoute(builder: (_) => DashBoard()),
                              //   (route) => false,
                              // );

                              carsBloc.add(GetCars());
                              /*uncomment if you need to get full username*/

                              //
                              // } else {
                              //   Navigator.pushAndRemoveUntil(
                              //       context,
                              //       CupertinoPageRoute(
                              //           builder: (_) => FullNamePage()),
                              //       (Route<dynamic> route) => false);
                              // }
                            }
                          },
                          child: BlocBuilder(
                            bloc: _bloc,
                            builder: (context, state) {
                              return Column(
                                mainAxisAlignment: MainAxisAlignment.start,
                                crossAxisAlignment: CrossAxisAlignment.start,
                                children: [
                                  SizedBox(
                                    height: 10.0.h,
                                    child: Row(
                                      mainAxisAlignment:
                                          MainAxisAlignment.spaceBetween,
                                      children: [
                                        InkWell(
                                          onTap: () => Navigator.pop(context),
                                          child: Padding(
                                            padding: EdgeInsets.all(5.0.w),
                                            child: Text(
                                              "${S.of(context).back}",
                                              style: AppStyle.textStyle()
                                                  .copyWith(
                                                      color: Color(0xFF959595),
                                                      fontWeight:
                                                          FontWeight.w500,
                                                      fontSize: 17.0),
                                            ),
                                          ),
                                        ),
                                        ValueListenableBuilder(
                                            valueListenable: timeLeftInSeconds!,
                                            builder: (context, left, _) {
                                              if (left == 0) {
                                                return InkWell(
                                                  onTap: () {
                                                    smsCode.clear();
                                                    setState(() {
                                                      loading = true;
                                                    });
                                                    _bloc.add(
                                                      SMSSendingEvent(
                                                        phone:
                                                            widget.phoneNumber,
                                                      ),
                                                    );
                                                    timeLeftInSeconds!.value =
                                                        60;
                                                  },
                                                  child: Padding(
                                                    padding:
                                                        EdgeInsets.all(5.0.w),
                                                    child: Text(
                                                      "${S.of(context).send_again}",
                                                      style: AppStyle
                                                              .textStyle()
                                                          .copyWith(
                                                              color: Color(
                                                                  0xff282828),
                                                              fontWeight:
                                                                  FontWeight
                                                                      .w600,
                                                              fontSize: 17.0),
                                                    ),
                                                  ),
                                                );
                                              }
                                              return SizedBox();
                                            }),
                                      ],
                                    ),
                                  ),
                                  SizedBox(height: 5.0.h),
                                  Container(
                                    margin:
                                        EdgeInsets.symmetric(horizontal: 3.0),
                                    height: 12.0.h,
                                    decoration: BoxDecoration(
                                      image: DecorationImage(
                                        image: AssetImage(
                                            "assets/png/auth_mobile_img.png"),
                                        fit: BoxFit.fitHeight,
                                        alignment: Alignment.centerLeft,
                                      ),
                                    ),
                                  ),
                                  const SizedBox(height: 30.0),
                                  Padding(
                                    padding:
                                        EdgeInsets.symmetric(horizontal: 5.0.w),
                                    child: Text(
                                      "${S.of(context).phone_verification(widget.phoneNumber)}",
                                      style: AppStyle.textStyle().copyWith(
                                          color: Color(0xff282828),
                                          fontWeight: FontWeight.bold,
                                          fontSize: 24.0),
                                    ),
                                  ),
                                  SizedBox(height: 2.0.h),
                                  Padding(
                                    padding: EdgeInsets.symmetric(
                                      horizontal: 5.0.w,
                                    ),
                                    child: Text(
                                      S.of(context).enter_sms_code,
                                      style: AppStyle.textStyle().copyWith(
                                          color: Color(0xFF959595),
                                          fontWeight: FontWeight.normal,
                                          fontSize: 14.0),
                                    ),
                                  ),
                                  Row(
                                    crossAxisAlignment:
                                        CrossAxisAlignment.center,
                                    children: [
                                      SizedBox(width: 5.0.w),
                                      SizedBox(
                                        width: 40.0.w,
                                        child: TextField(
                                          inputFormatters: [
                                            CustomTextInputFormatter(6),
                                          ],
                                          autofocus: true,
                                          keyboardType: TextInputType.phone,
                                          textInputAction: TextInputAction.done,
                                          controller: smsCode,
                                          textAlign: TextAlign.left,
                                          style: AppStyle.textStyle().copyWith(
                                            color: Color(0xff282828),
                                            fontSize: 30.0,
                                            fontWeight: FontWeight.bold,
                                          ),
                                          decoration: InputDecoration(
                                            hintText: "● ● ● ● ● ●",
                                            hintStyle: TextStyle(
                                              color: Color(0xffBDBDBD),
                                              fontSize: 13.0,
                                              fontWeight: FontWeight.bold,
                                            ),
                                            border: InputBorder.none,
                                          ),
                                        ),
                                      ),
                                      SizedBox(width: 5.0.w),
                                      ValueListenableBuilder(
                                        valueListenable: timeLeftInSeconds!,
                                        builder: (context, int 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 Padding(
                                            padding: EdgeInsets.symmetric(
                                                horizontal: 8.0),
                                            child: Text(
                                              '$minutesToShow:$secondsToShow',
                                            ),
                                          );
                                        },
                                      ),
                                    ],
                                  ),
                                  ValueListenableBuilder(
                                      valueListenable: timeLeftInSeconds!,
                                      builder: (context, left, _) {
                                        if (left == 0)
                                          return Expanded(
                                            child: Container(
                                              width: double.infinity,
                                              alignment: Alignment.center,
                                              child: GestureDetector(
                                                onTap: () {
                                                  Navigator.push(context,
                                                      MaterialPageRoute(
                                                          builder: (_) {
                                                    return SupportChatPage(
                                                      phoneNumber:
                                                          widget.phoneNumber,
                                                    );
                                                  }));
                                                  // launch(
                                                  //   "https://t.me/road24uz_feedback_bot",
                                                  //   forceSafariVC: false,
                                                  // );
                                                },
                                                child: Text(
                                                  S
                                                      .of(context)
                                                      .write_call_center,
                                                  style: AppStyle.textStyle()
                                                      .copyWith(
                                                    color:
                                                        AppColors.color2d9cdb,
                                                    fontWeight:
                                                        FontWeight.normal,
                                                    fontSize: 14.0,
                                                    decoration: TextDecoration
                                                        .underline,
                                                  ),
                                                ),
                                              ),
                                            ),
                                          );
                                        return const SizedBox();
                                      }),
                                  const Spacer(),
                                ],
                              );
                            },
                          ),
                        ),
                      ),
                    ),
                  ),
                ),
              )
            : NoConnectionScreen(
                onTap: () {
                  Navigator.pop(context);
                },
              );
      },
    );
  }
}
