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:flutter_svg/flutter_svg.dart';
import 'package:modal_progress_hud_nsn/modal_progress_hud_nsn.dart';
import 'package:road24_mobile/utils/check_internet.dart';
import 'package:road24_mobile/data/http/ApiException.dart';
import 'package:road24_mobile/data/repository/CarsRepository.dart';
import 'package:road24_mobile/data/repository/DevicesRepository.dart';
import 'package:road24_mobile/model/blocs/mycar/cars_bloc.dart';
import 'package:road24_mobile/model/models/AddCarModel.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/frequent_widgets.dart';
import 'package:road24_mobile/view/auth/phone_page.dart';
import 'package:road24_mobile/view/built/i18n.dart';
import 'package:road24_mobile/view/home/dash_board.dart';
import 'package:road24_mobile/view/mycar/add/add_new_car_licence_dialog.dart';
import 'package:road24_mobile/view/mycar/add/add_new_car_second_step.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/items/car_number_textfield.dart';
import 'package:road24_mobile/view/widgets/items/info_button.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 'add_new_car_law_page.dart';

class AddNewCarFirstStep extends StatefulWidget {
  final bool isFromRegistrationPage;
  final bool isFromMain;
  const AddNewCarFirstStep({
    this.isFromRegistrationPage = false,
    this.isFromMain = false,
  });

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

class _AddNewCarFirstStepState extends State<AddNewCarFirstStep>
    with TickerProviderStateMixin {
  static late AnimationController _controller;

  late Animation<double> scaleAnimation;

  var bloc = CarsBloc(repository: CarsRepository());

  bool _isSnackBarActive = false;

  List<String> techSeriesChoice = [
    'AAF',
    "AAC",
    "AAE",
    "AAB",
    "AFF",
    "VLO",
    "VL"
  ];

  // void _checkCarExistence() {
  //   print("car existance");

  //   bloc.add(CheckCarExistence(
  //       plateNumber: carNumber.text.trim(),
  //       techNumber: techNumber.text.trim()));
  // }

  var techNumber = TextEditingController();

  var carNumber = TextEditingController();

  var number = TextEditingController();

  static late GlobalKey<ScaffoldState> scaffoldKey;

  static late GlobalKey<FormState> formKey;

  var done = false;

  var isEdit = false;

  var loading = false;

  var buttonEnabled = true;

  var isError = false;

  var _chosenValue = "AAF";

  var isValidatoinError = false;

  var isValidatoinTechError = false;

  @override
  void initState() {
    super.initState();
    _controller = AnimationController(
      duration: const Duration(seconds: 2),
      vsync: this,
      lowerBound: 0.5,
      upperBound: 1.0,
    )..repeat(reverse: true);
    scaffoldKey = GlobalKey();
    formKey = GlobalKey();
    scaleAnimation = Tween(
      begin: 0.8,
      end: 1.2,
    ).animate(new CurvedAnimation(parent: _controller, curve: Curves.ease));
  }

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

  @override
  void dispose() {
    bloc.close();
    scaleAnimation.removeListener(() {});
    try {
      _controller.dispose();
    } catch (e) {}
    techNumber.dispose();
    carNumber.dispose();
    number.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return ValueListenableBuilder(
      valueListenable: MyApp.hasInternet,
      builder: (context, bool hasInternet, _) {
        return (hasInternet)
            ? ModalProgressHUD(
                inAsyncCall: loading,
                dismissible: false,
                color: AppColors.unSelectedColor,
                progressIndicator: const CircularProgressIndicator(
                  strokeWidth: 3.0,
                  valueColor: AlwaysStoppedAnimation<Color>(
                    AppColors.unSelectedColor,
                  ),
                ),
                child: GestureDetector(
                  onTap: () => FocusManager.instance.primaryFocus?.unfocus(),
                  child: Scaffold(
                    key: scaffoldKey,
                    resizeToAvoidBottomInset: false,
                    backgroundColor: AppColors.appPrimaryColor,
                    appBar: appBar(context),
                    body: BlocListener(
                      bloc: bloc,
                      listener: (context, state) {
                        if (state is CarsInitial) {
                          setState(() {
                            loading = true;
                          });
                        } else if (state is CarsLoadingError) {
                          setState(() {
                            loading = false;
                            isError = true;
                          });
                          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();
                                }
                                print(e);
                                Config.showSnackBar(context, text.toString());
                              }
                            }
                            _isSnackBarActive = false;
                          }
                        } else if (state is CarExistResult) {
                          AddCarModel.carNumber =
                              carNumber.text.toUpperCase().trim();

                          AddCarModel.tecNumber =
                              techNumber.text.trim().substring(3);

                          AddCarModel.tecSeries =
                              techNumber.text.trim().substring(0, 3);

                          Navigator.push(
                                  context,
                                  CupertinoPageRoute(
                                      builder: (_) => AddNewCarSecondStep()))
                              .then((value) => setState(() {
                                    loading = false;
                                  }));
                        }
                      },
                      child: Form(
                        key: formKey,
                        child: Column(
                          children: [
                            Expanded(
                              child: ListView(
                                shrinkWrap: true,
                                padding: const EdgeInsets.symmetric(
                                    horizontal: 16.0),
                                children: [
                                  const SizedBox(height: 6.0),
                                  Column(
                                    mainAxisAlignment: MainAxisAlignment.start,
                                    children: [
                                      SizedBox(
                                        width:
                                            MediaQuery.of(context).size.width *
                                                0.75,
                                        child: Row(
                                          children: [
                                            Text(
                                              S.of(context).car_number,
                                              maxLines: 1,
                                              overflow: TextOverflow.ellipsis,
                                              style: AppStyle.textStyle()
                                                  .copyWith(
                                                      color: Color(0xFF959595),
                                                      fontSize: 15.0,
                                                      fontWeight:
                                                          FontWeight.normal),
                                            ),
                                            Text(
                                              '*',
                                              style: AppStyle.textStyle()
                                                  .copyWith(
                                                      color: Color(0xffF51A51),
                                                      fontSize: 17.0,
                                                      fontWeight:
                                                          FontWeight.normal),
                                            ),
                                          ],
                                        ),
                                      ),
                                      Align(
                                        alignment: Alignment.center,
                                        child: Container(
                                          // margin: EdgeInsets.symmetric(
                                          //     horizontal: 12),
                                          height: 54,
                                          child: CarNumberField(
                                              context: context,
                                              textEditingControllerRegion:
                                                  carNumber,
                                              textEditingControllerNumber:
                                                  number,
                                              width: MediaQuery.of(context)
                                                      .size
                                                      .width *
                                                  0.75,
                                              fontSize: 24),
                                        ),
                                      ),
                                      if (isValidatoinError)
                                        SizedBox(
                                          width: MediaQuery.of(context)
                                                  .size
                                                  .width *
                                              0.75,
                                          child: Align(
                                            alignment: Alignment.centerLeft,
                                            child: Padding(
                                              padding: const EdgeInsets.only(
                                                  top: 6.0, left: 15),
                                              child: Text(
                                                S.of(context).car_number_error,
                                                textAlign: TextAlign.start,
                                                style: TextStyle(
                                                    color: Colors.red[700],
                                                    fontSize: 12.5),
                                              ),
                                            ),
                                          ),
                                        ),
                                      // SizedBox(height: 4.0),

                                      techNumberField(context),
                                      // widgetText(
                                      //     S.of(context).tec_series, techNumber,
                                      //     hintText: "AAF0123456"),
                                      const SizedBox(height: 20.0),
                                      Container(
                                        height: 100,
                                        width: double.infinity,
                                        decoration: BoxDecoration(
                                            borderRadius:
                                                BorderRadius.circular(12),
                                            border: Border.all(
                                                width: 0.4,
                                                color: Colors.grey)),
                                        child: ClipRRect(
                                          borderRadius:
                                              BorderRadius.circular(12),
                                          child: ScaleTransition(
                                            scale: scaleAnimation,
                                            alignment: Alignment.centerRight,
                                            child: Image.asset(
                                              "assets/png/driver_licence2.png",
                                              fit: BoxFit.fitWidth,
                                              alignment: Alignment.topRight,
                                            ),
                                          ),
                                        ),
                                      ),
                                    ],
                                  ),
                                  const SizedBox(height: 20.0),
                                  if (isError)
                                    Container(
                                      width: double.infinity,
                                      alignment: Alignment.center,
                                      margin: const EdgeInsets.only(bottom: 20),
                                      child: GestureDetector(
                                        onTap: () {
                                          Navigator.push(context,
                                              MaterialPageRoute(
                                            builder: (_) {
                                              return const SupportChatPage();
                                            },
                                          ));
                                        },
                                        child: Text(
                                          S.of(context).write_call_center,
                                          style: AppStyle.textStyle().copyWith(
                                            color: AppColors.color2d9cdb,
                                            fontWeight: FontWeight.normal,
                                            fontSize: 14.0,
                                            decoration:
                                                TextDecoration.underline,
                                          ),
                                        ),
                                      ),
                                    ),
                                  // SizedBox(height: 6.0),
                                  Center(
                                    child: InfoButtonWidget(
                                      onClicked: () {
                                        Navigator.push(
                                          context,
                                          CupertinoPageRoute(
                                            builder: (_) =>
                                                const AddNewCarLawPage(),
                                          ),
                                        );
                                      },
                                      svgName: 'info',
                                      title: S
                                          .of(context)
                                          .my_car_important_to_know,
                                    ),
                                  ),
                                  const SizedBox(height: 24.0),
                                ],
                              ),
                            ),
                            Padding(
                              padding:
                                  const EdgeInsets.symmetric(horizontal: 16.0),
                              child: Row(
                                children: [
                                  if (!widget.isFromRegistrationPage)
                                    Expanded(
                                      flex: 1,
                                      child: Container(
                                        decoration: BoxDecoration(
                                          color: Color(0xffE1E1E1),
                                          borderRadius:
                                              BorderRadius.circular(12.0),
                                        ),
                                        child: InkWell(
                                          onTap: () {
                                            print("is From register: " +
                                                widget.isFromRegistrationPage
                                                    .toString());
                                            if (widget.isFromRegistrationPage) {
                                              DashBoard.activeTab.value =
                                                  CustomBottomTabBar
                                                      .indexMap['MyAvto']!;
                                              Navigator.pushAndRemoveUntil(
                                                context,
                                                CupertinoPageRoute(
                                                    builder: (_) =>
                                                        DashBoard()),
                                                (route) => false,
                                              );
                                            } else
                                              Navigator.pop(context);
                                          },
                                          child: Container(
                                            height: 60.0,
                                            padding: const EdgeInsets.symmetric(
                                                horizontal: 15.0,
                                                vertical: 9.0),
                                            decoration: BoxDecoration(
                                              borderRadius:
                                                  BorderRadius.circular(32.0),
                                            ),
                                            child: Center(
                                              child: Text(
                                                "${S.of(context).close}",
                                                maxLines: 1,
                                                overflow: TextOverflow.ellipsis,
                                                style: AppStyle.textStyle()
                                                    .copyWith(
                                                  color: Color(0xff333333),
                                                  fontSize: 16.0,
                                                  fontWeight: FontWeight.w600,
                                                ),
                                              ),
                                            ),
                                          ),
                                        ),
                                      ),
                                    ),
                                  if (!widget.isFromRegistrationPage)
                                    SizedBox(width: 4.0.w),
                                  Expanded(
                                    flex: 2,
                                    child: submitButton(context),
                                  ),
                                ],
                              ),
                            ),
                            const SizedBox(height: 30.0),
                          ],
                        ),
                      ),
                    ),
                  ),
                ),
                // }
              )
            : NoConnectionScreen(
                onTap: () {
                  checkInternet();
                },
              );
      },
    );
  }

  SizedBox techNumberField(BuildContext context) {
    return SizedBox(
      width: MediaQuery.of(context).size.width * 0.75,
      child: Column(
        children: [
          Padding(
            padding: EdgeInsets.symmetric(horizontal: 1.w),
            child: Row(
              children: [
                Text(
                  S.of(context).tec_number_long,
                  maxLines: 1,
                  overflow: TextOverflow.ellipsis,
                  style: AppStyle.textStyle().copyWith(
                      color: Color(0xFF959595),
                      fontSize: 15.0,
                      fontWeight: FontWeight.normal),
                ),
                Text(
                  '*',
                  style: AppStyle.textStyle().copyWith(
                      color: Color(0xffF51A51),
                      fontSize: 17.0,
                      fontWeight: FontWeight.normal),
                ),
              ],
            ),
          ),
          Row(
            mainAxisAlignment: MainAxisAlignment.start,
            children: [
              Container(
                height: 54.0,
                padding: const EdgeInsets.symmetric(horizontal: 15.0),
                margin: const EdgeInsets.symmetric(vertical: 6.0),
                decoration: BoxDecoration(
                  border: Border.all(color: Color(0xFFE0E0E0)),
                  borderRadius: BorderRadius.circular(12.0),
                  color: Colors.white,
                ),
                child: Center(
                  child: DropdownButton<String>(
                    value: _chosenValue,
                    isExpanded: false,
                    underline: SizedBox(),
                    items: techSeriesChoice.map((String value) {
                      return DropdownMenuItem<String>(
                        value: value,
                        child: Text(
                          value,
                          style: AppStyle.textStyle().copyWith(
                            color: AppColors.selectedColor,
                            fontSize: 17.0,
                            fontWeight: FontWeight.normal,
                          ),
                        ),
                      );
                    }).toList(),
                    onChanged: (String? value) {
                      if (value != null)
                        setState(() {
                          _chosenValue = value;
                        });
                      // setState(() {
                      //   kind = value!;
                      //   AddInsuranceModel.kind =
                      //       kindVariationsToSend[
                      //           kindVariations
                      //               .indexOf(
                      //                   kind!)];
                      // });
                    },
                    hint: Text(
                      '${S.of(context).choose}',
                      style: TextStyle(
                        fontSize: 17.0,
                        fontWeight: FontWeight.w300,
                      ),
                    ),
                  ),
                ),
              ),
              Expanded(
                child: TextFormField(
                  cursorColor: AppColors.selectedColor,
                  textAlign: TextAlign.left,
                  controller: techNumber,
                  autofocus: false,
                  keyboardType: TextInputType.number,
                  textInputAction: TextInputAction.next,
                  // onEditingComplete: () =>
                  //     node?.nextFocus(),
                  inputFormatters: [
                    CustomTextInputFormatter(7),
                    FilteringTextInputFormatter.allow(RegExp("[a-zA-Z0-9]")),
                    UpperCaseTextFormatter(),
                  ],
                  enabled: !isEdit,
                  style: AppStyle.textStyle()
                      .copyWith(
                        color: Color(0xff282828),
                        fontSize: 17.0,
                        fontWeight: FontWeight.normal,
                      )
                      .copyWith(
                        color: !isEdit ? null : AppColors.unSelectedColor,
                      ),
                  decoration: InputDecoration(
                      hintText: "1234567",
                      floatingLabelBehavior: FloatingLabelBehavior.always,
                      hintStyle: TextStyle(
                        fontSize: 17.0,
                        color: Color(0xff959595),
                      ),
                      border: OutlineInputBorder(
                        borderRadius: BorderRadius.circular(12.0),
                        // borderSide: BorderSide(
                        //     color: Colors
                        //         .transparent),
                      ),
                      suffixIcon: isEdit ? SizedBox() : faqSuffixIcon(context),
                      enabledBorder: OutlineInputBorder(
                        borderRadius: BorderRadius.circular(12.0),
                        borderSide: BorderSide(
                            color: isValidatoinTechError
                                ? (Colors.red[700]!)
                                : Color(0xFFE0E0E0),
                            width: 1),
                      ),
                      fillColor: Colors.white,
                      filled: true,
                      focusedBorder: OutlineInputBorder(
                        borderRadius: BorderRadius.circular(12.0),
                        borderSide: BorderSide(color: Colors.black, width: 1),
                      ),
                      contentPadding: const EdgeInsets.all(15.0),
                      errorText: null),
                  validator: (value) {
                    if (value!.isEmpty) {
                      return S.of(context).validationForEmpty;
                    } else if (value.length != 7) {
                      return S.of(context).invalidInfo;
                    } else {
                      return null;
                    }
                  },
                ),
              ),
            ],
          ),
          if (isValidatoinTechError) validationText(context),
        ],
      ),
    );
  }

  InkWell submitButton(BuildContext context) {
    return InkWell(
      onTap: !buttonEnabled
          ? null
          : () async {
              setState(() => buttonEnabled = false);
              var carPlateNumber = carNumber.text.toUpperCase().trim() +
                  number.text.toUpperCase().trim();
              if (techNumber.text.trim().length == 7 &&
                  carPlateNumber.trim().length > 5) {
                setState(() {
                  isValidatoinError = false;
                  isValidatoinTechError = false;
                });

                // _checkCarExistence();
                AddCarModel.carNumber = carPlateNumber;

                AddCarModel.tecNumber = techNumber.text.trim();

                AddCarModel.tecSeries = _chosenValue;

                Navigator.push(
                        context,
                        CupertinoPageRoute(
                            builder: (_) => AddNewCarSecondStep()))
                    .then((value) => setState(() {
                          loading = false;
                        }));
              } else {
                setState(() {});
                Config.showSnackBar(context, S.of(context).please_fill_all);
              }
              if (techNumber.text.trim().length != 7) {
                setState(() {
                  isValidatoinTechError = true;
                });
              } else {
                setState(() {
                  isValidatoinTechError = false;
                });
              }
              if (carPlateNumber.trim().length < 5) {
                setState(() {
                  isValidatoinError = true;
                });
              } else {
                setState(() {
                  isValidatoinError = false;
                });
              }
              setState(() => buttonEnabled = true);
            },
      child: Container(
        height: 60.0,
        padding: const 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).next,
              maxLines: 1,
              overflow: TextOverflow.ellipsis,
              style: AppStyle.textStyle().copyWith(
                  color: Colors.white,
                  fontWeight: FontWeight.w600,
                  fontSize: 16.0),
              textAlign: TextAlign.center,
            ),
            const SizedBox(width: 6.0),
          ],
        ),
      ),
    );
  }

  SizedBox validationText(BuildContext context) {
    return SizedBox(
      width: MediaQuery.of(context).size.width * 0.75,
      child: Align(
        alignment: Alignment.centerLeft,
        child: Padding(
          padding: const EdgeInsets.only(top: 6.0, left: 15),
          child: Text(
            S.of(context).validationForMinimumNumber(7),
            textAlign: TextAlign.start,
            style: TextStyle(color: Colors.red[700], fontSize: 12.5),
          ),
        ),
      ),
    );
  }

  GestureDetector faqSuffixIcon(BuildContext context) {
    return GestureDetector(
      onTap: () {
        AddNewCarLicenceDialog.show(context);
      },
      child: Container(
        width: 0,
        margin: const EdgeInsets.only(left: 20, right: 5),
        alignment: Alignment.center,
        color: Colors.transparent,
        child: SvgPicture.asset(
          "assets/svg/manual_faq.svg",
          color: AppColors.colorf51a51,
          height: 18,
        ),
      ),
    );
  }

  AppBar appBar(BuildContext context) {
    return AppBar(
      toolbarHeight: 60.0,
      leading: Material(
        type: MaterialType.transparency,
        child: InkWell(
          onTap: () {
            if (widget.isFromRegistrationPage) {
              setTokens(null, null);
              Navigator.pushAndRemoveUntil(
                context,
                CupertinoPageRoute(builder: (_) => const PhonePage()),
                (route) => false,
              );
            } else
              Navigator.pop(context);
          },
          child: Container(
            margin: const EdgeInsets.all(10.0),
            decoration: 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_car}",
        maxLines: 1,
        overflow: TextOverflow.ellipsis,
        style: AppStyle.textStyle().copyWith(
            color: Colors.black, fontWeight: FontWeight.w600, fontSize: 17.0),
      ),
    );
  }

  enableRefreshingPage() {
    FrequentWidgets.carNeedToRefresh();
    // MyCarPage.needToRefresh.value = true;
  }
}
