import 'dart:convert';
import 'dart:io';
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/data/response/CarsResponse.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/my_car_page.dart';
import 'package:road24_mobile/view/mycar/add/add_new_car_licence_dialog.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/no_connection_screen.dart';
import 'package:road24_mobile/view/widgets/success_page.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 'select_brand_model_widget/widgets.dart';
import 'add_new_car_law_page.dart';

class AddNewCarOrEditPage extends StatefulWidget {
  final Results? carDetails;
  final bool isFromRegistrationPage;
  final bool isFromMain;
  const AddNewCarOrEditPage({
    this.carDetails,
    this.isFromRegistrationPage = false,
    this.isFromMain = false,
  });

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

class _AddNewCarOrEditPageState extends State<AddNewCarOrEditPage>
    implements SelectBrandImp, SelectModelImp, SelectPhotoImp {
  CarsBloc bloc = CarsBloc(repository: CarsRepository());
  bool _isSnackBarActive = false;

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

  void _editCar(int id) {
    bloc.add(EditCar(
      id,
      fileName: "$modelFileName",
      filePath: modelFileImage?.path,
    ));
  }

  void _deleteCar(int id) {
    bloc.add(DeleteCar(id));
  }

  final FocusNode? node = FocusNode();

  late TextEditingController carNumber;
  late TextEditingController series;
  late TextEditingController number;
  late TextEditingController brand;
  late TextEditingController model;
  final GlobalKey<ScaffoldState> scaffoldKey = GlobalKey();
  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;

  @override
  void initState() {
    super.initState();
    if (widget.carDetails != null) {
      final car = widget.carDetails;
      AddCarModel.carNumber = car?.number;
      AddCarModel.tecNumber = car?.techPassNum;
      AddCarModel.tecSeries = car?.techPassSeries;
      AddCarModel.mark = car?.brand;
      AddCarModel.name = car?.model;
      AddCarModel.brandId = car?.carBrand?.id;
      AddCarModel.modelId = car?.carModel?.id;
      AddCarModel.imageId = car?.image?.id;
      carNumber = TextEditingController(text: car?.number);
      series = TextEditingController(text: car?.techPassSeries);
      number = TextEditingController(text: car?.techPassNum);
      brand = TextEditingController(text: car?.brand);
      model = TextEditingController(text: car?.model);
      brandId = car?.carBrand?.id;
      modelId = car?.carModel?.id;
      modelImageId = car?.image?.id;
      brandImage = car?.carBrand?.logo?.file;
      modelImage = car?.image?.file;
    } else {
      carNumber = TextEditingController();
      series = TextEditingController();
      number = TextEditingController();
      brand = TextEditingController();
      model = TextEditingController();
      AddCarModel.tecSeries = null;
    }
    if (AddCarModel.tecSeries != null) isEdit = 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;
    carNumber.dispose();
    series.dispose();
    number.dispose();
    brand.dispose();
    node?.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: const CircularProgressIndicator(
                  strokeWidth: 3.0,
                  valueColor: AlwaysStoppedAnimation<Color>(
                    AppColors.unSelectedColor,
                  ),
                ),
                child: GestureDetector(
                  onTap: () {
                    FocusScope.of(context).requestFocus(new FocusNode());
                  },
                  child: Scaffold(
                    key: scaffoldKey,
                    backgroundColor: AppColors.appPrimaryColor,
                    appBar: (!done) ? appBar(context) : null,
                    body: BlocListener(
                      bloc: bloc,
                      listener: (context, state) async {
                        if (state is AddCarSuccessState) {
                          done = true;
                          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: () {},
                              ),
                            ),
                          );
                        }
                        if (state is EditCarSuccessState) {
                          done = true;
                          setState(() {
                            loading = false;
                          });
                          Navigator.pushReplacement(
                            context,
                            CupertinoPageRoute(
                              builder: (context) => SuccessPage(
                                text: S.of(context).success,
                                subText: S.of(context).edit_car_success_ins,
                                onTap: () {
                                  DashBoard.activeTab.value =
                                      CustomBottomTabBar.indexMap['MyAvto']!;
                                  Navigator.pop(context);

                                  enableRefreshingPage();
                                  // MyCarPage.needToRefresh.value = true;
                                },
                                // onTapSkip: () {},
                              ),
                            ),
                          );
                        }
                        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;
                          }
                        }
                        if (state is DeleteCarSuccessState) {
                          print("success deletion");
                          setState(() => loading = false);

                          if (MyCarPage.current != null) {
                            MyCarPage.current = MyCarPage.current! - 1;

                            if (MyCarPage.current! < 0)
                              MyCarPage.current = null;
                          }

                          Navigator.pushReplacement(
                            context,
                            CupertinoPageRoute(
                              builder: (context) => SuccessPage(
                                text: S.of(context).success,
                                subText: S.of(context).edit_car_success_ins,
                                onTap: () {
                                  DashBoard.activeTab.value =
                                      CustomBottomTabBar.indexMap['MyAvto']!;
                                  Navigator.pop(context);

                                  enableRefreshingPage();

                                  if (widget.isFromMain) {
                                    Navigator.pop(context);
                                  }
                                  // MyCarPage.needToRefresh.value = true;
                                },
                                // onTapSkip: () {},
                              ),
                            ),
                          );
                        }
                      },
                      child: BlocBuilder(
                        bloc: bloc,
                        builder: (context, state) {
                          return SingleChildScrollView(
                            child: Form(
                              key: formKey,
                              child: Column(
                                children: [
                                  const SizedBox(height: 6.0),
                                  GestureDetector(
                                    onTap: () {
                                      Navigator.push(
                                        context,
                                        CupertinoPageRoute(
                                          builder: (_) =>
                                              const AddNewCarLawPage(),
                                        ),
                                      );
                                    },
                                    child: Container(
                                      margin: const EdgeInsets.symmetric(
                                        horizontal: 14,
                                      ),
                                      padding: const EdgeInsets.all(12),
                                      decoration: BoxDecoration(
                                        color: Colors.white,
                                        borderRadius: BorderRadius.circular(16),
                                      ),
                                      child: Row(
                                        children: [
                                          Container(
                                            padding: const EdgeInsets.all(8),
                                            decoration: BoxDecoration(
                                              color: AppColors.appPrimaryColor,
                                              shape: BoxShape.circle,
                                            ),
                                            child: SvgPicture.asset(
                                              "assets/svg/info.svg",
                                              height: 20,
                                            ),
                                          ),
                                          const SizedBox(width: 12),
                                          Text(
                                            S
                                                .of(context)
                                                .my_car_important_to_know,
                                            style:
                                                AppStyle.textStyle().copyWith(
                                              color: Color(0xff282828),
                                              fontSize: 16,
                                              fontWeight: FontWeight.w500,
                                            ),
                                          ),
                                          const Spacer(),
                                          const Icon(
                                            Icons.chevron_right,
                                            color: Color(0xFF858585),
                                          ),
                                        ],
                                      ),
                                    ),
                                  ),
                                  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),
                                        Padding(
                                          padding: EdgeInsets.symmetric(
                                              horizontal: 1.0.w),
                                          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),
                                              ),
                                            ],
                                          ),
                                        ),
                                        TextFormField(
                                          cursorColor: AppColors.selectedColor,
                                          textAlign: TextAlign.left,
                                          controller: carNumber,
                                          autofocus: false,
                                          focusNode: node,
                                          keyboardType: TextInputType.text,
                                          textInputAction: TextInputAction.next,
                                          // onEditingComplete: () =>
                                          //     node?.nextFocus(),
                                          inputFormatters: [
                                            CustomTextInputFormatter(10),
                                            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: "00 A 000 AA",
                                            hintStyle: TextStyle(
                                              fontSize: 17.0,
                                              color: Color(0xff959595),
                                            ),
                                            border: OutlineInputBorder(
                                              borderRadius:
                                                  BorderRadius.circular(12.0),
                                              borderSide: BorderSide(
                                                  color: Colors.transparent),
                                            ),
                                            suffixIcon: isEdit
                                                ? SizedBox()
                                                : 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,
                                                      ),
                                                    ),
                                                  ),
                                            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:
                                                const EdgeInsets.all(15.0),
                                          ),
                                          validator: (value) {
                                            if (value!.isEmpty) {
                                              return S
                                                  .of(context)
                                                  .validationForEmpty;
                                            } else {
                                              return null;
                                            }
                                          },
                                        ),
                                        const SizedBox(height: 15.0),
                                        techNumberBlock(context),
                                        techNumberBlockSery(context),
                                        const SizedBox(height: 15.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: [
                                            if (!widget.isFromRegistrationPage)
                                              Expanded(
                                                flex: 1,
                                                child: Container(
                                                  decoration: BoxDecoration(
                                                    color: Color(0xffE1E1E1),
                                                    borderRadius:
                                                        BorderRadius.circular(
                                                            12.0),
                                                  ),
                                                  child: InkWell(
                                                    onTap: () {
                                                      if (MyApp
                                                          .hasInternet.value) {
                                                        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),
                                            submitButton(context),
                                          ],
                                        ),
                                        const SizedBox(height: 15.0),
                                      ],
                                    ),
                                  ),
                                ],
                              ),
                            ),
                          );
                        },
                      ),
                    ),
                  ),
                ),
              )
            : NoConnectionScreen(
                onTap: () {
                  checkInternet();
                },
              );
      },
    );
  }

  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: (_) => 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(
        widget.isFromRegistrationPage
            ? "${S.of(context).add_car}"
            : "${S.of(context).my_car}",
        maxLines: 1,
        overflow: TextOverflow.ellipsis,
        style: AppStyle.textStyle().copyWith(
            color: Colors.black, fontWeight: FontWeight.w600, fontSize: 17.0),
      ),
      actions: [
        if (widget.carDetails != null)
          Padding(
            padding: const EdgeInsets.symmetric(horizontal: 15.0),
            child: InkWell(
              onTap: () {
                CustomDialog(
                  title: S.of(context).delete,
                  content: S.of(context).delete_car_content,
                  onNoTap: () {
                    Navigator.of(context).pop();
                  },
                  onYesTap: () {
                    // Navigator.of(context).pop();
                    setState(() {
                      loading = true;
                    });
                    _deleteCar(widget.carDetails!.id);
                  },
                ).showAlertDialog(context);
              },
              child: Container(
                width: 38.0,
                height: 38.0,
                decoration: BoxDecoration(
                    color: Colors.white,
                    shape: BoxShape.circle,
                    border: Border.all(color: AppColors.colorf51a51)),
                child: Center(
                  child: SvgPicture.asset("assets/svg/delete.svg",
                      color: AppColors.colorf51a51, width: 18.0),
                ),
              ),
            ),
          ),
      ],
    );
  }

  Expanded submitButton(BuildContext context) {
    return Expanded(
      flex: 2,
      child: InkWell(
        onTap: !buttonEnabled
            ? null
            : () async {
                setState(() => buttonEnabled = false);
                if (formKey.currentState!.validate()) {
                  print("is valid");
                  AddCarModel.carNumber = carNumber.text.toString();
                  AddCarModel.tecNumber = number.text.toString();
                  AddCarModel.tecSeries = series.text.toString();
                  AddCarModel.mark = brand.text.toString();
                  AddCarModel.name = model.text.toString();
                  setState(() {
                    if (widget.carDetails != null) {
                      loading = true;
                      _editCar(widget.carDetails!.id);
                    } else {
                      loading = true;
                      _isSnackBarActive = false;
                      _addCar();
                    }
                  });
                } else {
                  print("is not valid");
                  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(
                (widget.carDetails != null)
                    ? S.of(context).save
                    : 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),
            ],
          ),
        ),
      ),
    );
  }

  Row techNumberBlockSery(BuildContext context) {
    return Row(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Expanded(
          flex: 2,
          child: TextFormField(
            cursorColor: AppColors.selectedColor,
            maxLines: 1,
            textInputAction: TextInputAction.next,
            inputFormatters: [
              CustomTextInputFormatter(3),
              FilteringTextInputFormatter.allow(RegExp("[a-zA-Z]")),
              UpperCaseTextFormatter(),
            ],
            keyboardType: TextInputType.text,
            controller: series,
            textAlign: TextAlign.left,
            // onEditingComplete: () =>
            //     node?.nextFocus(),
            enabled: !isEdit,
            style: AppStyle.textStyle()
                .copyWith(
                  color: Color(0xff282828),
                  fontSize: 17.0,
                  fontWeight: FontWeight.normal,
                )
                .copyWith(
                  color: !isEdit ? null : AppColors.unSelectedColor,
                ),
            decoration: InputDecoration(
              hintText: 'AAA',
              hintStyle: TextStyle(
                fontSize: 17.0,
                color: Color(0xff959595),
              ),
              errorMaxLines: 2,
              border: OutlineInputBorder(
                borderRadius: BorderRadius.circular(12.0),
                borderSide: BorderSide(color: Colors.transparent),
              ),
              suffixIcon: isEdit
                  ? SizedBox()
                  : 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,
                        ),
                      ),
                    ),
              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).copyWith(
                right: 0,
              ),
            ),
            validator: (value) {
              if (value!.length <= 2) {
                return S.of(context).validationForMinimumNumber(3);
              } else {
                return null;
              }
            },
          ),
        ),
        const SizedBox(width: 15.0),
        Expanded(
          flex: 3,
          child: TextFormField(
              cursorColor: AppColors.selectedColor,
              maxLines: 1,
              inputFormatters: [
                CustomTextInputFormatter(7),
                FilteringTextInputFormatter.allow(RegExp("[0-9]")),
              ],
              keyboardType: TextInputType.number,
              controller: number,
              textAlign: TextAlign.left,
              enabled: !isEdit,
              style: AppStyle.textStyle()
                  .copyWith(
                    color: Color(0xff282828),
                    fontSize: 17.0,
                    fontWeight: FontWeight.normal,
                  )
                  .copyWith(
                    color: !isEdit ? null : AppColors.unSelectedColor,
                  ),
              decoration: InputDecoration(
                hintText: '0123456',
                hintStyle: AppStyle.textStyle().copyWith(
                  color: AppColors.unSelectedColor,
                  fontSize: 17.0,
                  fontWeight: FontWeight.normal,
                ),
                suffixIcon: isEdit
                    ? SizedBox()
                    : 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,
                          ),
                        ),
                      ),
                border: OutlineInputBorder(
                  borderRadius: BorderRadius.circular(12.0),
                  borderSide: BorderSide(color: Colors.transparent),
                ),
                errorMaxLines: 2,
                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: const EdgeInsets.all(15.0),
              ),
              validator: (value) {
                if (value!.length <= 6) {
                  return S.of(context).validationForMinimumNumber(7);
                } else {
                  return null;
                }
              }),
        ),
      ],
    );
  }

  Row techNumberBlock(BuildContext context) {
    return Row(
      children: [
        Expanded(
          flex: 2,
          child: Padding(
            padding: EdgeInsets.symmetric(horizontal: 1.0.w),
            child: Row(
              children: [
                Flexible(
                  child: Text(
                    "${S.of(context).tec_series}",
                    maxLines: 2,
                    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),
                ),
              ],
            ),
          ),
        ),
        const SizedBox(width: 15.0),
        Expanded(
          flex: 3,
          child: Padding(
            padding: EdgeInsets.symmetric(horizontal: 1.0.w),
            child: Row(
              children: [
                Flexible(
                  child: Text(
                    "${S.of(context).tec_number}",
                    maxLines: 2,
                    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),
                ),
              ],
            ),
          ),
        ),
      ],
    );
  }

  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;
    });
  }
}
