import 'dart:convert';
import 'dart:io';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.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/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/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/custom_dialog.dart';
import 'package:road24_mobile/view/widgets/items/car_number.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/success_page.dart';
import 'package:road24_mobile/utils/extensions.dart';
import 'package:sizer/sizer.dart';
import 'select_brand_model_widget/widgets.dart';
import 'add_new_car_law_page.dart';

class AddNewCarSecondStep extends StatefulWidget {
  @override
  _AddNewCarSecondStepState createState() => _AddNewCarSecondStepState();
}

class _AddNewCarSecondStepState extends State<AddNewCarSecondStep>
    implements SelectBrandImp, SelectModelImp, SelectPhotoImp {
  CarsBloc bloc = CarsBloc(repository: CarsRepository());

  bool _isSnackBarActive = false;

  void _addCar() {
    bloc.add(AddCar(
      fileName: "$modelFileName",
      filePath: modelFileImage?.path,
    ));
  }

  var brand = TextEditingController();
  var model = TextEditingController();
  final GlobalKey<FormState> formKey = GlobalKey();
  int? brandId;
  int? modelId;
  int? modelImageId;
  String? brandImage;
  String? modelImage;
  String? modelFileName;
  File? modelFileImage;

  bool done = false;
  bool isEdit = false;
  bool loading = false;
  bool buttonEnabled = true;

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

  @override
  void dispose() {
    bloc.close();

    AddCarModel.carNumber = '';
    AddCarModel.tecNumber = '';
    AddCarModel.tecSeries = '';
    AddCarModel.mark = '';
    AddCarModel.name = '';
    modelImage = null;
    modelFileImage = null;
    modelId = null;
    modelFileName = null;
    AddCarModel.imageId = null;
    brand.dispose();
    model.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: CircularProgressIndicator(
                  strokeWidth: 3.0,
                  valueColor: AlwaysStoppedAnimation<Color>(
                    AppColors.unSelectedColor,
                  ),
                ),
                child: GestureDetector(
                  onTap: () {
                    FocusScope.of(context).requestFocus(FocusNode());
                  },
                  child: Scaffold(
                    backgroundColor: AppColors.appPrimaryColor,
                    appBar: AppBar(
                      toolbarHeight: 60.0,
                      leading: Material(
                        type: MaterialType.transparency,
                        child: InkWell(
                          onTap: () {
                            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: CarNumber(
                        carNumber: AddCarModel.carNumber!,
                      ),
                      // Text(
                      //   "${AddCarModel.carNumber}",
                      //   maxLines: 1,
                      //   overflow: TextOverflow.ellipsis,
                      //   style: AppStyle.textStyle().copyWith(
                      //       color: Colors.black,
                      //       fontWeight: FontWeight.w600,
                      //       fontSize: 17.0),
                      // ),
                    ),
                    body: BlocListener(
                      bloc: bloc,
                      listener: (context, state) {
                        if (state is AddCarSuccessState) {
                          setState(() {
                            loading = false;
                          });

                          Navigator.pushReplacement(
                            context,
                            CupertinoPageRoute(
                              builder: (context) => SuccessPage(
                                text: S.of(context).success,
                                subText: S.of(context).add_car_success_ins,
                                onTap: () {
                                  DashBoard.activeTab.value =
                                      CustomBottomTabBar.indexMap['MyAvto']!;
                                  // if (widget.isFromRegistrationPage) {
                                  Navigator.pushAndRemoveUntil(
                                    context,
                                    CupertinoPageRoute(
                                        builder: (_) => DashBoard()),
                                    (route) => false,
                                  );
                                  // } else {
                                  //   Navigator.pop(context);
                                  // }

                                  enableRefreshingPage();
                                  // MyCarPage.needToRefresh.value = true;
                                },
                                // onTapSkip: () {},
                              ),
                            ),
                          );
                        } else if (state is CarsLoadingError) {
                          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: Column(
                                children: [
                                  const SizedBox(height: 6.0),
                                  importToKnow(context),
                                  const SizedBox(height: 6.0),
                                  Container(
                                    padding: const EdgeInsets.symmetric(
                                        horizontal: 15.0),
                                    decoration: BoxDecoration(
                                      color: AppColors.appPrimaryColor,
                                      borderRadius: BorderRadius.only(
                                        topLeft: Radius.circular(7.0),
                                        topRight: Radius.circular(7.0),
                                      ),
                                    ),
                                    child: Column(
                                      crossAxisAlignment:
                                          CrossAxisAlignment.start,
                                      children: [
                                        const SizedBox(height: 6.0),
                                        Row(
                                          children: [
                                            Text(
                                              S.of(context).mark_of_car,
                                              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),
                                            ),
                                          ],
                                        ),
                                        SelectBrandWidget(
                                          controller: brand,
                                          hintText: "Chevrolet",
                                          imageUrl: brandImage,
                                          onTap: () {
                                            SelectBrandDialog.show(
                                              context,
                                              title: S.of(context).mark_of_car,
                                              imp: this,
                                            );
                                          },
                                        ),
                                        const SizedBox(height: 15.0),
                                        Row(
                                          children: [
                                            Text(
                                              "${S.of(context).vehicle_name}",
                                              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),
                                            ),
                                          ],
                                        ),
                                        SelectModelWidget(
                                          controller: model,
                                          hintText: "Malibu",
                                          onTap: () {
                                            SelectModelDialog.show(
                                              context,
                                              title: S.of(context).vehicle_name,
                                              brandId: brandId,
                                              imp: this,
                                            );
                                          },
                                        ),
                                        const SizedBox(height: 15.0),
                                        Text(
                                          S.of(context).add_car_photo,
                                          maxLines: 1,
                                          overflow: TextOverflow.ellipsis,
                                          style: AppStyle.textStyle().copyWith(
                                              color: Color(0xFF959595),
                                              fontSize: 15.0,
                                              fontWeight: FontWeight.normal),
                                        ),
                                        const SizedBox(height: 12.0),
                                        SelectPhotoWidget(
                                          imageUrl: modelImage,
                                          imageFile: modelFileImage,
                                          ratioX: 3.5,
                                          ratioY: 3,
                                          onEditPressed: () {
                                            SelectPhotoDialog.show(
                                              context,
                                              title:
                                                  S.of(context).add_car_photo,
                                              imp: this,
                                              ratioX: 4,
                                              ratioY: 3,
                                            );
                                          },
                                          onDeletePressed: () {
                                            CustomDialog(
                                              title: S.of(context).delete,
                                              content: S
                                                  .of(context)
                                                  .delete_car_image_content,
                                              onNoTap: () {
                                                Navigator.of(context).pop();
                                              },
                                              onYesTap: () {
                                                setState(() {
                                                  modelImage = null;
                                                  modelFileImage = null;
                                                  modelId = null;
                                                  modelFileName = null;
                                                  AddCarModel.imageId = null;
                                                });
                                                Navigator.of(context).pop();
                                              },
                                            ).showAlertDialog(context);
                                          },
                                        ),
                                        const SizedBox(height: 12.0),
                                        Container(
                                          width: double.infinity,
                                          alignment: Alignment.center,
                                          child: !(state is CarsLoadingError)
                                              ? null
                                              : GestureDetector(
                                                  onTap: () {
                                                    Navigator.push(context,
                                                        MaterialPageRoute(
                                                      builder: (_) {
                                                        return 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,
                                                    ),
                                                  ),
                                                ),
                                        ),
                                        const SizedBox(height: 35.0),
                                        Row(
                                          children: [
                                            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,
                                                        ),
                                                      ),
                                                    ),
                                                  ),
                                                ),
                                              ),
                                            ),
                                            SizedBox(width: 4.0.w),
                                            submitButton(context),
                                          ],
                                        ),
                                        const SizedBox(height: 15.0),
                                      ],
                                    ),
                                  ),
                                ],
                              ),
                            ),
                          );
                        },
                      ),
                    ),
                  ),
                ),
              )
            : NoConnectionScreen(
                onTap: () {
                  checkInternet();
                },
              );
      },
    );
  }

  Padding importToKnow(BuildContext context) {
    return Padding(
      padding: const EdgeInsets.symmetric(horizontal: 15.0),
      child: InfoButtonWidget(
        onClicked: () {
          Navigator.push(
            context,
            CupertinoPageRoute(
              builder: (_) => AddNewCarLawPage(),
            ),
          );
        },
        svgName: 'info',
        title: S.of(context).my_car_important_to_know,
      ),
    );
  }

  Expanded submitButton(BuildContext context) {
    return Expanded(
      flex: 2,
      child: InkWell(
        onTap: !buttonEnabled
            ? null
            : () async {
                setState(() => buttonEnabled = false);
                if (formKey.currentState!.validate()) {
                  AddCarModel.mark = brand.text.toString();
                  AddCarModel.name = model.text.toString();
                  setState(() {
                    loading = true;
                    _isSnackBarActive = false;
                    _addCar();
                  });
                } else {
                  setState(() {});
                  Config.showSnackBar(
                    context,
                    S.of(context).please_fill_all,
                  );
                }
                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).add,
                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),
            ],
          ),
        ),
      ),
    );
  }

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

  @override
  void onUpdateBrand({String brandName = '', String? imageUrl, int? brandId}) {
    setState(() {
      this.brand.text = brandName;
      this.brandImage = imageUrl;
      this.brandId = brandId;
      AddCarModel.brandId = brandId;
    });
  }

  @override
  void onUpdateModel({String modelName = '', int? modelId}) {
    setState(() {
      this.model.text = modelName;
      this.modelId = modelId;
      AddCarModel.modelId = modelId;
    });
  }

  @override
  void onUpdateImage({String? fileName, File? file}) async {
    setState(() {
      this.modelFileName = fileName;
      this.modelFileImage = file;
      AddCarModel.imageId = null;
    });
  }
}
