import 'dart:convert';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.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/http/ApiException.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/my_app.dart';
import 'package:road24_mobile/utils/card_scanner.dart';
import 'package:road24_mobile/view/built/i18n.dart';
import 'package:road24_mobile/view/mycar/add/inspection/widgets/custom_bottom_sheet.dart';
import 'package:road24_mobile/view/settings/card/add/sms_verification_for_card_page.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/text_field_custom_formatter.dart';
import 'package:road24_mobile/utils/extensions.dart';

class AddCardPage extends StatefulWidget {
  @override
  _AddCardPageState createState() => _AddCardPageState();
}

class _AddCardPageState extends State<AddCardPage> {
  final bloc = CardBloc(repository: CardRepository());
  final cardNumberController = TextEditingController();
  final expireController = TextEditingController();
  final nameController = TextEditingController();

  bool loading = false;
  bool _isSnackBarActive = false;
  bool buttonEnabled = true;
  final scaffoldKey = GlobalKey<ScaffoldState>();
  final formKey = GlobalKey<FormState>();
  var focusNode = FocusNode();

  @override
  void dispose() {
    cardNumberController.dispose();
    expireController.dispose();
    nameController.dispose();
    focusNode.dispose();
    bloc.close();
    super.dispose();
  }

  void _addCard() {
    bloc.add(
      AddCardEvent(
        cardNumber: cardNumberController.text.replaceAll(" ", ""),
        expire: expireController.text.replaceAll("/", ""),
        name: nameController.text,
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    return ValueListenableBuilder<bool>(
      valueListenable: MyApp.hasInternet,
      builder: (context, hasInternet, _) {
        return (hasInternet)
            ? ModalProgressHUD(
                inAsyncCall: loading,
                dismissible: false,
                color: AppColors.unSelectedColor,
                progressIndicator: CircularProgressIndicator(
                  strokeWidth: 3.0,
                  valueColor: AlwaysStoppedAnimation(AppColors.unSelectedColor),
                ),
                child: GestureDetector(
                  onTap: () => FocusScope.of(context).unfocus(),
                  child: Scaffold(
                    bottomSheet: CustomBottomSheet(
                      onTap: () async {
                        if (!buttonEnabled)
                          return null;
                        else {
                          setState(() {
                            buttonEnabled = false;
                            loading = true;
                          });
                          if (formKey.currentState!.validate()) {
                            _addCard();
                          } else {
                            setState(() {
                              loading = false;
                            });
                            Config.showSnackBar(
                              context,
                              S.of(context).please_fill_all,
                            );
                          }
                          await Future.delayed(Duration(milliseconds: 2500));
                          setState(() => buttonEnabled = true);
                        }
                      },
                      buttonColor: Colors.black,
                      title: '${S.of(context).add_card}',
                    ),
                    key: scaffoldKey,
                    backgroundColor: AppColors.appPrimaryColor,
                    appBar: AppBar(
                      backgroundColor: Colors.transparent,
                      toolbarHeight: 60.0,
                      leading: Material(
                        type: MaterialType.transparency,
                        child: InkWell(
                          onTap: () => Navigator.pop(context),
                          child: Container(
                            margin: EdgeInsets.all(10.0),
                            decoration: const BoxDecoration(
                              color: Color(0xffDFDFDF),
                              shape: BoxShape.circle,
                            ),
                            child: const Center(
                              child: Icon(
                                Icons.arrow_back_ios_rounded,
                                size: 20.0,
                                color: Colors.black,
                              ),
                            ),
                          ),
                        ),
                      ),
                      title: Text(
                        "${S.of(context).add_card}",
                        style: AppStyle.textStyle().copyWith(
                            color: Colors.black,
                            fontWeight: FontWeight.w600,
                            fontSize: 17.0),
                      ),
                    ),
                    body: BlocListener(
                      bloc: bloc,
                      listener: (context, state) async {
                        if (state is AddCardSuccessState) {
                          setState(() => loading = false);
                          final bool? hasResult = await Navigator.push(
                            context,
                            CupertinoPageRoute(
                              builder: (context) => SmsVerificationForCardPage(
                                cardId: state.response.id,
                              ),
                            ),
                          );
                          if (hasResult != null && hasResult)
                            Navigator.pop(context);
                        }
                        if (state is CardLoadingError) {
                          setState(() => loading = false);
                          if (!_isSnackBarActive) {
                            _isSnackBarActive = true;
                            try {
                              Config.showSnackBar(
                                context,
                                json
                                    .decode(ApiException.errorMessage.value
                                        .toString())
                                    .values
                                    .first
                                    .first
                                    .toString(),
                              );
                            } catch (e) {
                              try {
                                Config.showSnackBar(
                                  context,
                                  json
                                      .decode(ApiException.errorMessage.value
                                          .toString())
                                      .values
                                      .first
                                      .toString(),
                                );
                              } catch (e) {
                                String text = "";
                                try {
                                  text =
                                      state.exception.toString().getErrorText();
                                } catch (ex) {
                                  text = state.exception.toString();
                                }

                                Config.showSnackBar(
                                  context,
                                  text,
                                );
                              }
                            }

                            _isSnackBarActive = false;
                          }
                        }
                      },
                      child: BlocBuilder(
                        bloc: bloc,
                        builder: (context, state) {
                          return SingleChildScrollView(
                            child: Form(
                              key: formKey,
                              child: Container(
                                padding: EdgeInsets.symmetric(horizontal: 15.0),
                                decoration: BoxDecoration(
                                  borderRadius: BorderRadius.only(
                                    topLeft: Radius.circular(7.0),
                                    topRight: Radius.circular(7.0),
                                  ),
                                ),
                                child: Column(
                                  crossAxisAlignment: CrossAxisAlignment.start,
                                  children: [
                                    Text(
                                      "${S.of(context).card_number}",
                                      style: AppStyle.textStyle().copyWith(
                                          color: Color(0xFF959595),
                                          fontSize: 15.0,
                                          fontWeight: FontWeight.normal),
                                    ),
                                    const SizedBox(height: 5.0),
                                    cardNumberField(context),
                                    const SizedBox(height: 15.0),
                                    Text(
                                      "${S.of(context).date_expired}",
                                      style: AppStyle.textStyle().copyWith(
                                          color: Color(0xFF959595),
                                          fontSize: 15.0,
                                          fontWeight: FontWeight.normal),
                                    ),
                                    const SizedBox(height: 5.0),
                                    expireField(context),
                                    const SizedBox(height: 15.0),
                                    Text(
                                      "${S.of(context).name_of_card}",
                                      style: AppStyle.textStyle().copyWith(
                                          color: Color(0xFF959595),
                                          fontSize: 15.0,
                                          fontWeight: FontWeight.normal),
                                    ),
                                    const SizedBox(height: 5.0),
                                    cardNameField(context),
                                    const SizedBox(height: 15.0),
                                    // InkWell(
                                    //   onTap: !buttonEnabled
                                    //       ? null
                                    //       : () async {
                                    //           setState(() {
                                    //             buttonEnabled = false;
                                    //             loading = true;
                                    //           });
                                    //           if (formKey.currentState!
                                    //               .validate()) {
                                    //             _addCard();
                                    //           } else {
                                    //             setState(() {
                                    //               loading = false;
                                    //             });
                                    //             Config.showSnackBar(
                                    //               context,
                                    //               S.of(context).please_fill_all,
                                    //             );
                                    //           }
                                    //           await Future.delayed(
                                    //               Duration(milliseconds: 2500));
                                    //           setState(
                                    //               () => buttonEnabled = true);
                                    //         },
                                    //   child: Container(
                                    //     height: 60.0,
                                    //     padding: EdgeInsets.symmetric(
                                    //         horizontal: 15.0, vertical: 9.0),
                                    //     decoration: BoxDecoration(
                                    //       color: Colors.black,
                                    //       borderRadius:
                                    //           BorderRadius.circular(12.0),
                                    //     ),
                                    //     child: Row(
                                    //       mainAxisAlignment:
                                    //           MainAxisAlignment.center,
                                    //       children: [
                                    //         const SizedBox(width: 6.0),
                                    //         Text(
                                    //           S.of(context).add,
                                    //           style: AppStyle.textStyle()
                                    //               .copyWith(
                                    //                   color: Colors.white,
                                    //                   fontWeight:
                                    //                       FontWeight.w600,
                                    //                   fontSize: 16.0),
                                    //           textAlign: TextAlign.center,
                                    //           maxLines: 1,
                                    //           overflow: TextOverflow.ellipsis,
                                    //         ),
                                    //         const SizedBox(width: 6.0),
                                    //       ],
                                    //     ),
                                    //   ),
                                    // ),

                                    // const SizedBox(height: 15.0),
                                  ],
                                ),
                              ),
                            ),
                          );
                        },
                      ),
                    ),
                  ),
                ),
              )
            : NoConnectionScreen(
                onTap: () {
                  Navigator.pushReplacement(
                    context,
                    FadeRoute(page: AddCardPage()),
                  );
                },
              );
      },
    );
  }

  TextFormField cardNameField(BuildContext context) {
    return TextFormField(
      cursorColor: AppColors.selectedColor,
      maxLines: 1,
      inputFormatters: [
        CustomTextInputFormatter(20),
      ],
      keyboardType: TextInputType.text,
      textCapitalization: TextCapitalization.sentences,
      controller: nameController,
      textAlign: TextAlign.left,
      style: AppStyle.textStyle().copyWith(
        color: Color(0xff282828),
        fontSize: 17.0,
        fontWeight: FontWeight.normal,
      ),
      decoration: InputDecoration(
        hintText: S.of(context).enter_card_name,
        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 {
          return null;
        }
      },
    );
  }

  TextFormField expireField(BuildContext context) {
    return TextFormField(
      cursorColor: AppColors.selectedColor,
      maxLines: 1,
      // onEditingComplete: () {
      //   try {
      //     node?.nextFocus();
      //   } catch (ex) {}
      // },
      inputFormatters: [
        MaskTextInputFormatter(
          mask: '##/##',
          initialText: expireController.text,
        ),
      ],
      keyboardType: TextInputType.number,
      textCapitalization: TextCapitalization.sentences,
      controller: expireController,
      textAlign: TextAlign.left,
      style: AppStyle.textStyle().copyWith(
        color: Color(0xff282828),
        fontSize: 17.0,
        fontWeight: FontWeight.normal,
      ),
      decoration: InputDecoration(
        hintText: S.of(context).enter_card_expire,
        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 == 4) {
            return null;
          } else {
            return S.of(context).validationForMinimumNumber(4);
          }
        }
      },
    );
  }

  TextFormField cardNumberField(BuildContext context) {
    return TextFormField(
      focusNode: focusNode,
      onTap: () async {
        FocusScope.of(context).unfocus();
        await Future.delayed(Duration.zero);
        focusNode.requestFocus();
      },
      cursorColor: AppColors.selectedColor,
      maxLines: 1,
      inputFormatters: [
        MaskTextInputFormatter(
          mask: '#### #### #### ####',
        ),
      ],
      keyboardType: TextInputType.number,
      textCapitalization: TextCapitalization.sentences,
      controller: cardNumberController,
      textAlign: TextAlign.left,
      // autofocus: true,
      style: AppStyle.textStyle().copyWith(
        color: Color(0xff282828),
        fontSize: 17.0,
        fontWeight: FontWeight.normal,
      ),
      decoration: InputDecoration(
        hintText: "0000 0000 0000 0000",
        hintStyle: AppStyle.textStyle().copyWith(
          color: AppColors.unSelectedColor,
          fontSize: 17.0,
          fontWeight: FontWeight.normal,
        ),
        suffixIcon: InkWell(
          child: Icon(
            Icons.qr_code_scanner,
            size: 25.0,
            color: AppColors.selectedColor,
          ),
          onTap: () {
            scanCard(
              context,
              cardNumberController,
              expireController,
            );
          },
        ),
        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);
          }
        }
      },
    );
  }
}
