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:modal_progress_hud_nsn/modal_progress_hud_nsn.dart';
import 'package:road24_mobile/data/http/ApiException.dart';
import 'package:road24_mobile/data/repository/CarsRepository.dart';
import 'package:road24_mobile/data/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/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/widgets/custom_bottom_tabbar.dart';
import 'package:road24_mobile/view/widgets/fade_route.dart';
import 'package:road24_mobile/view/widgets/no_connection_screen.dart';
import 'package:road24_mobile/view/widgets/success_page.dart';
import 'package:road24_mobile/view/widgets/text_field_custom_formatter.dart';
import 'package:road24_mobile/utils/extensions.dart';

import 'inspection/widgets/custom_appbar.dart';
import 'inspection/widgets/custom_details_text.dart';

class OilPage extends StatefulWidget {
  final Oil? oil;

  const OilPage({Key? key, this.oil}) : super(key: key);

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

class _OilPageState extends State<OilPage> {
  var loading = false;
  var _carsBloc = CarsBloc(repository: CarsRepository());
  GlobalKey<FormState> _key = GlobalKey();
  late TextEditingController lastReplacementController;
  late TextEditingController mileageController;
  late TextEditingController markController;
  late TextEditingController chargePriceController;
  late TextEditingController nextReplacementController;
  late TextEditingController nextMileAgeController;
  late TextEditingController dailyMileAgeController;
  late TextEditingController oilMileAgeController;

  var chosenTime = DateTime.now();

  @override
  void initState() {
    if (widget.oil != null) {
      var oil = widget.oil!;

      mileageController = TextEditingController(text: oil.mileage.toString());

      nextMileAgeController =
          TextEditingController(text: oil.nextMileage.toString());

      markController = TextEditingController(text: oil.mark);

      chargePriceController =
          TextEditingController(text: oil.chargePrice.toString());

      chosenTime = DateTime.parse(oil.lastReplacement);

      lastReplacementController = TextEditingController(
          text: DateTime.parse(oil.lastReplacement).dateToStr());

      nextReplacementController = TextEditingController(
          text: DateTime.parse(oil.nextReplacement).dateToStr());

      dailyMileAgeController = TextEditingController();

      oilMileAgeController = TextEditingController();

      if (oil.dailyMileage != null) {
        dailyMileAgeController.text = oil.dailyMileage.toString();
        oilMileAgeController.text = oil.oilMileage.toString();
      }
    } else {
      mileageController = TextEditingController();
      lastReplacementController = TextEditingController();
      nextMileAgeController = TextEditingController();
      nextReplacementController = TextEditingController();
      markController = TextEditingController();
      chargePriceController = TextEditingController();
      dailyMileAgeController = TextEditingController();
      oilMileAgeController = TextEditingController();
    }

    dailyMileAgeController.addListener(() {
      calculateNextReplacement();
    });

    oilMileAgeController.addListener(() {
      calculateNextReplacement();
    });

    mileageController.addListener(() {
      calculateNextReplacement();
    });

    lastReplacementController.addListener(() {
      calculateNextReplacement();
    });

    super.initState();
  }

  calculateNextReplacement() {
    var dailyMileage = dailyMileAgeController.text;

    var oilMileage = oilMileAgeController.text;

    var mileage = mileageController.text;

    if (oilMileage.isNotEmpty &&
        dailyMileage.isNotEmpty &&
        !dailyMileage.startsWith("0") &&
        !oilMileage.startsWith("0") &&
        dailyMileage.length > 0 &&
        oilMileage.length > 1 &&
        mileage.isNotEmpty &&
        mileage.length > 1) {
      _carsBloc.add(OilCalculateNextDate(
          lastOilDate: chosenTime,
          dailyMileage: int.tryParse(dailyMileage) ?? 1,
          oilInterval: int.tryParse(oilMileage) ?? 1,
          mileage: int.tryParse(mileage) ?? 1));
    }
  }

  @override
  void dispose() {
    mileageController.dispose();
    lastReplacementController.dispose();
    nextMileAgeController.dispose();
    nextReplacementController.dispose();
    markController.dispose();
    chargePriceController.dispose();
    dailyMileAgeController.dispose();
    oilMileAgeController.dispose();
    _carsBloc.close();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return ValueListenableBuilder(
      valueListenable: MyApp.hasInternet,
      builder: (context, bool hasInternet, _) {
        return (hasInternet)
            ? ModalProgressHUD(
                inAsyncCall: loading,
                color: AppColors.unSelectedColor,
                progressIndicator: CircularProgressIndicator(
                  strokeWidth: 3.0,
                  valueColor: AlwaysStoppedAnimation<Color>(
                    AppColors.unSelectedColor,
                  ),
                ),
                child: GestureDetector(
                  onTap: () {
                    FocusScope.of(context).requestFocus(FocusNode());
                  },
                  child: Scaffold(
                    appBar: CustomAppBar(titleText: S.of(context).oil),
                    body: BlocListener(
                      listener: (context, state) {
                        if (state is EditCarSuccessState) {
                          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);
                                  MyCarPage.needToRefresh.value = true;
                                },
                                // onTapSkip: () {},
                              ),
                            ),
                          );
                        }
                        if (state is CarsLoadingError) {
                          setState(() {
                            loading = false;
                          });
                          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,
                              );
                            }
                          }
                        }
                      },
                      bloc: _carsBloc,
                      child: BlocBuilder(
                        bloc: _carsBloc,
                        builder: (context, state) {
                          if (state is OilNextReplaceCalculated) {
                            nextMileAgeController.text =
                                state.nextMileage.toString();
                            nextReplacementController.text =
                                state.nextReplacementDate.toString();
                          }
                          return Form(
                            key: _key,
                            child: Column(
                              children: [
                                Expanded(
                                  child: ListView(
                                    padding:
                                        EdgeInsets.symmetric(horizontal: 15.0),
                                    children: [
                                      SizedBox(height: 8.0),
                                      // if (nextMileAgeController
                                      //         .text.isNotEmpty &&
                                      //     nextReplacementController
                                      //         .text.isNotEmpty)
                                      Column(
                                        children: [
                                          CustomDetailsText(
                                            title: S
                                                .of(context)
                                                .date_next_replacement
                                                .toUpperCase(),
                                            content: nextReplacementController
                                                    .text.isNotEmpty
                                                ? nextReplacementController.text
                                                : "---",
                                          ),
                                          SizedBox(height: 8.0),
                                          CustomDetailsText(
                                            title: S
                                                .of(context)
                                                .next_mileage
                                                .toUpperCase(),
                                            content: nextMileAgeController
                                                    .text.isNotEmpty
                                                ? "${nextMileAgeController.text} ${S.of(context).km}"
                                                : "---",
                                          ),
                                          SizedBox(height: 8.0),
                                          Divider(),
                                        ],
                                      ),
                                      SizedBox(height: 8.0),
                                      Row(
                                        mainAxisAlignment:
                                            MainAxisAlignment.spaceBetween,
                                        crossAxisAlignment:
                                            CrossAxisAlignment.start,
                                        children: [
                                          Expanded(
                                            flex: 1,
                                            child: _textWidget(S
                                                .of(context)
                                                .date_last_replacement),
                                          ),
                                          SizedBox(width: 15.0),
                                          Expanded(
                                            flex: 1,
                                            child: _textWidget(
                                                S.of(context).last_mileage),
                                          ),
                                        ],
                                      ),
                                      Row(
                                        crossAxisAlignment:
                                            CrossAxisAlignment.start,
                                        children: [
                                          Expanded(
                                            flex: 1,
                                            child: Container(
                                              // height: 50.0,
                                              margin: EdgeInsets.symmetric(
                                                  vertical: 3.0),
                                              child: InkWell(
                                                onTap: () {
                                                  showDatePicker(
                                                    context: context,
                                                    initialDate: DateTime.now(),
                                                    firstDate: DateTime(
                                                        DateTime.now().year -
                                                            20),
                                                    lastDate: DateTime.now(),
                                                    locale: Locale(
                                                        (Config.language !=
                                                                'oz')
                                                            ? Config.language
                                                            : 'uz'),
                                                  ).then(
                                                    (value) => {
                                                      this.setState(() {
                                                        try {
                                                          //   AddOilModel
                                                          //           .lastReplacement =
                                                          //       DateFormat(
                                                          //               'yyyy-MM-dd')
                                                          //           .format(
                                                          //               value!);
                                                          //   print(value);

                                                          if (value != null) {
                                                            chosenTime = value;

                                                            lastReplacementController
                                                                    .text =
                                                                value
                                                                    .dateToStr();
                                                          }
                                                        } catch (_) {}
                                                      }),
                                                    },
                                                  );
                                                },
                                                child: IgnorePointer(
                                                  ignoring: true,
                                                  child: _textFieldWidget(
                                                      lastReplacementController,
                                                      'дд.мм.гг'),
                                                ),
                                              ),
                                            ),
                                          ),
                                          SizedBox(width: 15.0),
                                          Expanded(
                                            flex: 1,
                                            child: Container(
                                              // height: 50.0,
                                              margin: EdgeInsets.symmetric(
                                                  vertical: 3.0),
                                              child: _textFieldWidget(
                                                  mileageController,
                                                  '00.0 ${S.of(context).km}'),
                                            ),
                                          ),
                                        ],
                                      ),
                                      SizedBox(height: 10.0),
                                      _textWidget(S.of(context).mark_of_oil),
                                      Container(
                                        // height: 50.0,
                                        margin:
                                            EdgeInsets.symmetric(vertical: 3.0),
                                        child: _textFieldWidget(markController,
                                            S.of(context).show_oil_mark,
                                            isText: true),
                                      ),
                                      // SizedBox(height: 10.0),
                                      // _textWidget(S.of(context).charge_price),
                                      // Container(
                                      //   // height: 50.0,
                                      //   margin:
                                      //       EdgeInsets.symmetric(vertical: 3.0),
                                      //   child: _textFieldWidget(
                                      //     chargePriceController,
                                      //     '00.0 ${S.of(context).uzs.toLowerCase()}',
                                      //   ),
                                      // ),
                                      SizedBox(height: 10.0),
                                      _textWidget(S.of(context).oilmileage),
                                      Container(
                                          // height: 50.0,
                                          margin: EdgeInsets.symmetric(
                                              vertical: 3.0),
                                          child: _textFieldWidget(
                                              oilMileAgeController,
                                              '00.0 ${S.of(context).km}')),
                                      SizedBox(height: 10.0),
                                      _textWidget(S.of(context).dailyMileage),
                                      Container(
                                          // height: 50.0,
                                          margin: EdgeInsets.symmetric(
                                              vertical: 3.0),
                                          child: _textFieldWidget(
                                              dailyMileAgeController,
                                              '00.0 ${S.of(context).km}')),
                                      SizedBox(height: 10.0),
                                      // Row(
                                      //   crossAxisAlignment:
                                      //       CrossAxisAlignment.start,
                                      //   mainAxisAlignment:
                                      //       MainAxisAlignment.spaceBetween,
                                      //   children: [
                                      //     Expanded(
                                      //         flex: 1,
                                      //         child: _textWidget(
                                      //             S.of(context).dailyMileage)),
                                      //     SizedBox(width: 15.0),
                                      //     Expanded(
                                      //         flex: 1,
                                      //         child: _textWidget(
                                      //             S.of(context).oilmileage)),
                                      //   ],
                                      // ),
                                      // Row(
                                      //   crossAxisAlignment:
                                      //       CrossAxisAlignment.start,
                                      //   children: [
                                      //     Expanded(
                                      //       flex: 1,
                                      //       child: Container(
                                      //         // height: 50.0,
                                      //         margin: EdgeInsets.symmetric(
                                      //             vertical: 3.0),
                                      //         child: _textFieldWidget(
                                      //           dailyMileAgeController,
                                      //           '00.0 ${S.of(context).km}',
                                      //         ),
                                      //       ),
                                      //     ),
                                      //     SizedBox(width: 15.0),
                                      //     Expanded(
                                      //       flex: 1,
                                      //       child: Container(
                                      //         margin: EdgeInsets.symmetric(
                                      //             vertical: 3.0),
                                      //         child: _textFieldWidget(
                                      //             oilMileAgeController,
                                      //             '00.0 ${S.of(context).km}'),
                                      //       ),
                                      //     ),
                                      //   ],
                                      // ),
                                    ],
                                  ),
                                ),
                                Row(
                                  children: [
                                    SizedBox(width: 15.0),
                                    Expanded(
                                      flex: 1,
                                      child: Container(
                                        decoration: BoxDecoration(
                                          color: Color(0xffE1E1E1),
                                          borderRadius:
                                              BorderRadius.circular(12.0),
                                        ),
                                        child: Material(
                                          borderRadius:
                                              BorderRadius.circular(32.0),
                                          type: MaterialType.transparency,
                                          shadowColor:
                                              Colors.white.withOpacity(0.3),
                                          child: InkWell(
                                            onTap: () {
                                              Navigator.pop(context);
                                            },
                                            child: Container(
                                              padding: EdgeInsets.symmetric(
                                                  horizontal: 15.0,
                                                  vertical: 15.0),
                                              decoration: BoxDecoration(
                                                borderRadius:
                                                    BorderRadius.circular(32.0),
                                              ),
                                              child: Center(
                                                child: Text(
                                                  "${S.of(context).close}",
                                                  style: AppStyle.textStyle()
                                                      .copyWith(
                                                    color: Color(0xff333333),
                                                    fontSize: 16.0,
                                                    fontWeight: FontWeight.w600,
                                                  ),
                                                  maxLines: 1,
                                                  overflow:
                                                      TextOverflow.ellipsis,
                                                ),
                                              ),
                                            ),
                                          ),
                                        ),
                                      ),
                                    ),
                                    SizedBox(width: 12.0),
                                    Expanded(
                                      flex: 2,
                                      child: Container(
                                        decoration: BoxDecoration(
                                          color: Colors.black,
                                          borderRadius:
                                              BorderRadius.circular(12.0),
                                        ),
                                        child: Material(
                                          borderRadius:
                                              BorderRadius.circular(32.0),
                                          type: MaterialType.transparency,
                                          shadowColor:
                                              Colors.white.withOpacity(0.3),
                                          child: InkWell(
                                            onTap: () {
                                              if (_key.currentState!
                                                  .validate()) {
                                                var model = AddOilModel();
                                                try {
                                                  model.mileage = int.parse(
                                                      mileageController.text);

                                                  model.mark =
                                                      markController.text;

                                                  model.chargePrice = 0;
                                                  // model.chargePrice = int.parse(
                                                  //     chargePriceController.text);

                                                  model.oilMileage = int.parse(
                                                      oilMileAgeController
                                                          .text);

                                                  model.dailyMileage =
                                                      int.parse(
                                                          dailyMileAgeController
                                                              .text);
                                                  if (model.dailyMileage == 0 ||
                                                      model.oilMileage == 0 ||
                                                      model.mileage == 0) {
                                                    throw Exception();
                                                  }
                                                  setState(() {
                                                    loading = true;
                                                  });
                                                  if (_key.currentState!
                                                      .validate()) {
                                                    _carsBloc.add(EditCarOil(
                                                        MyCarPage.currentId!,
                                                        model,
                                                        chosenTime));
                                                  } else {
                                                    setState(() {
                                                      loading = false;
                                                    });
                                                  }
                                                } catch (ex) {
                                                  Config.showSnackBar(
                                                    context,
                                                    S.of(context).invalidInfo,
                                                  );
                                                }
                                              } else {
                                                Config.showSnackBar(
                                                  context,
                                                  S.of(context).invalidInfo,
                                                );
                                              }
                                            },
                                            child: Container(
                                              padding: EdgeInsets.symmetric(
                                                  horizontal: 6.0,
                                                  vertical: 15.0),
                                              decoration: BoxDecoration(
                                                borderRadius:
                                                    BorderRadius.circular(32.0),
                                              ),
                                              child: Padding(
                                                padding: EdgeInsets.symmetric(
                                                    horizontal: 6.0),
                                                child: Text(
                                                  (widget.oil != null)
                                                      ? S.of(context).save
                                                      : S.of(context).add,
                                                  style: AppStyle.textStyle()
                                                      .copyWith(
                                                          color: Colors.white,
                                                          fontWeight:
                                                              FontWeight.w600,
                                                          fontSize: 16.0),
                                                  textAlign: TextAlign.center,
                                                  maxLines: 1,
                                                  overflow:
                                                      TextOverflow.ellipsis,
                                                ),
                                              ),
                                            ),
                                          ),
                                        ),
                                      ),
                                    ),
                                    SizedBox(width: 15.0),
                                  ],
                                ),
                                SizedBox(height: 30.0),
                              ],
                            ),
                          );
                        },
                      ),
                    ),
                  ),
                ),
              )
            : NoConnectionScreen(
                onTap: () {
                  Navigator.pushReplacement(
                    context,
                    FadeRoute(
                      page: OilPage(
                        oil: widget.oil,
                      ),
                    ),
                  );
                },
              );
      },
    );
  }

  _textWidget(String title) {
    return Text(
      title,
      style: AppStyle.textStyle().copyWith(
          color: Color(0xFF959595),
          fontSize: 15.0,
          fontWeight: FontWeight.normal),
    );
  }

  _textFieldWidget(TextEditingController _controller, String hint,
      {bool isText = false, bool readOnly = false}) {
    return TextFormField(
      cursorColor: AppColors.selectedColor,
      controller: _controller,
      readOnly: readOnly,
      keyboardType: isText ? TextInputType.text : TextInputType.number,
      inputFormatters: [
        CustomTextInputFormatter(isText ? 30 : 7),
      ],
      decoration: InputDecoration(
        hintText: hint,
        hintStyle: AppStyle.textStyle().copyWith(
          color: AppColors.unSelectedColor,
          fontSize: 17.0,
          fontWeight: FontWeight.normal,
        ),
        border: OutlineInputBorder(
          borderRadius: BorderRadius.circular(12.0),
          borderSide: BorderSide(color: Colors.transparent),
        ),
        enabledBorder: OutlineInputBorder(
          borderRadius: BorderRadius.circular(12.0),
          borderSide: BorderSide(color: Colors.transparent),
        ),
        fillColor: Color(0xffEFEFEF),
        filled: true,
        focusedBorder: OutlineInputBorder(
          borderRadius: BorderRadius.circular(12.0),
          borderSide: BorderSide(color: Colors.black, width: 1.5),
        ),
        contentPadding: EdgeInsets.all(15.0),
        errorMaxLines: 2,
      ),
      validator: (value) {
        // if (isNullable) {
        //   return null;
        // }
        if (value!.isEmpty) {
          print("is empty");
          return S.of(context).validationForEmpty;
        }
        if (value.startsWith("0") && _controller != lastReplacementController) {
          return S.of(context).invalidInfo;
        } else {
          return null;
        }
      },
    );
  }
}
