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/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 'package:intl/intl.dart';
import 'package:sizer/sizer.dart';

import 'inspection/widgets/custom_appbar.dart';

class TintingPage extends StatefulWidget {
  final bool? askingFirstTime;
  final Tinting? tinting;
  static List<String>? types;

  const TintingPage({Key? key, this.askingFirstTime, this.tinting})
      : super(key: key);

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

class _TintingPageState extends State<TintingPage> {
  bool loading = false;
  CarsBloc _carsBloc = CarsBloc(repository: CarsRepository());
  GlobalKey<FormState> _key = GlobalKey();
  String? typesValue;
  List<String> typesToSend = ['back', 'side'];
  late TextEditingController datePassedController;
  late TextEditingController dateEndController;
  late TextEditingController series;
  late TextEditingController number;

  @override
  void initState() {
    if (widget.tinting != null) {
      var tinting = widget.tinting!;
      series = TextEditingController(text: tinting.series);
      number = TextEditingController(text: tinting.number);
      datePassedController = TextEditingController(
          text: DateTime.parse(widget.tinting!.datePassed).dateToStr());

      dateEndController = TextEditingController(
          text: DateTime.parse(tinting.dateEnd).dateToStr());

      print(dateEndController.text);
      AddTintingModel.kind = tinting.kind;
      AddTintingModel.series = series.text;
      AddTintingModel.number = number.text;
      AddTintingModel.datePassed =
          DateFormat('yyyy-MM-dd').format(DateTime.parse(tinting.datePassed));
      AddTintingModel.dateEnd =
          DateFormat('yyyy-MM-dd').format(DateTime.parse(tinting.dateEnd));
    } else {
      series = TextEditingController();
      number = TextEditingController();
      datePassedController = TextEditingController();
      dateEndController = TextEditingController();
    }
    super.initState();
  }

  @override
  void dispose() {
    _carsBloc.close();
    AddTintingModel.kind = '';
    AddTintingModel.series = '';
    AddTintingModel.number = '';
    AddTintingModel.datePassed = '';
    AddTintingModel.dateEnd = '';
    datePassedController.dispose();
    dateEndController.dispose();
    series.dispose();
    number.dispose();
    _carsBloc.close();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    if (TintingPage.types == null) {
      TintingPage.types = [
        S.of(context).back_tinting,
        S.of(context).side_tinting,
      ];
    }
    if (typesValue == null) {
      if (widget.tinting == null) {
        typesValue = TintingPage.types![0];
        AddTintingModel.kind =
            typesToSend[TintingPage.types!.indexOf(typesValue!)];
      } else if (widget.tinting != null) {
        typesValue =
            TintingPage.types![typesToSend.indexOf(widget.tinting!.kind)];
        AddTintingModel.kind =
            typesToSend[TintingPage.types!.indexOf(typesValue!)];
      }
    }

    return ValueListenableBuilder(
        valueListenable: MyApp.hasInternet,
        builder: (context, hasInternet, _) {
          return (hasInternet as bool)
              ? ModalProgressHUD(
                  inAsyncCall: loading,
                  color: AppColors.unSelectedColor,
                  progressIndicator: CircularProgressIndicator(
                    strokeWidth: 3.0,
                    valueColor: AlwaysStoppedAnimation<Color>(
                      AppColors.unSelectedColor,
                    ),
                  ),
                  child: GestureDetector(
                    onTap: () {
                      FocusScope.of(context).requestFocus(new FocusNode());
                    },
                    child: Scaffold(
                      appBar: CustomAppBar(
                        titleText: S.of(context).tinting,
                      ),
                      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;
                            });
                          }
                        },
                        bloc: _carsBloc,
                        child: BlocBuilder(
                          bloc: _carsBloc,
                          builder: (context, state) {
                            return Form(
                              key: _key,
                              child: Column(
                                children: [
                                  Expanded(
                                    child: ListView(
                                      padding: EdgeInsets.symmetric(
                                          horizontal: 15.0),
                                      children: [
                                        SizedBox(
                                          height: 2.0.h,
                                        ),
                                        Text(
                                          "${S.of(context).validity}",
                                          style: AppStyle.textStyle().copyWith(
                                              color: Color(0xFF959595),
                                              fontSize: 15.0,
                                              fontWeight: FontWeight.normal),
                                        ),
                                        Row(
                                          children: [
                                            Expanded(
                                              flex: 1,
                                              child: Container(
                                                // height: 50.0,
                                                margin: EdgeInsets.symmetric(
                                                    vertical: 1.0.w),
                                                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 {
                                                            AddTintingModel
                                                                    .datePassed =
                                                                DateFormat(
                                                                        'yyyy-MM-dd')
                                                                    .format(
                                                                        value!);
                                                            print(value);
                                                            datePassedController
                                                                    .text =
                                                                value
                                                                    .dateToStr();
                                                          } catch (_) {}
                                                        }),
                                                      },
                                                    );
                                                  },
                                                  child: IgnorePointer(
                                                    ignoring: true,
                                                    child: TextFormField(
                                                      cursorColor: AppColors
                                                          .selectedColor,
                                                      controller:
                                                          datePassedController,
                                                      keyboardType:
                                                          TextInputType.text,
                                                      decoration:
                                                          InputDecoration(
                                                        hintText: 'дд.мм.гг',
                                                        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 (value!.isEmpty) {
                                                          return S
                                                              .of(context)
                                                              .validationForEmpty;
                                                        } else {
                                                          return null;
                                                        }
                                                      },
                                                    ),
                                                  ),
                                                ),
                                              ),
                                            ),
                                            SizedBox(width: 15.0),
                                            Expanded(
                                              flex: 1,
                                              child: Container(
                                                // height: 50.0,
                                                margin: EdgeInsets.symmetric(
                                                    vertical: 1.0.w),
                                                child: InkWell(
                                                  onTap: () {
                                                    showDatePicker(
                                                      context: context,
                                                      initialDate:
                                                          DateTime.now(),
                                                      firstDate: DateTime.now(),
                                                      lastDate: DateTime(
                                                          DateTime.now().year +
                                                              10),
                                                      locale: Locale(
                                                          (Config.language !=
                                                                  'oz')
                                                              ? Config.language
                                                              : 'uz'),
                                                    ).then(
                                                      (value) => {
                                                        this.setState(() {
                                                          try {
                                                            AddTintingModel
                                                                    .dateEnd =
                                                                DateFormat(
                                                                        'yyyy-MM-dd')
                                                                    .format(
                                                                        value!);
                                                            print(value);
                                                            dateEndController
                                                                    .text =
                                                                value
                                                                    .dateToStr();
                                                          } catch (_) {}
                                                        }),
                                                      },
                                                    );
                                                  },
                                                  child: IgnorePointer(
                                                    ignoring: true,
                                                    child: TextFormField(
                                                      cursorColor: AppColors
                                                          .selectedColor,
                                                      controller:
                                                          dateEndController,
                                                      keyboardType:
                                                          TextInputType.text,
                                                      decoration:
                                                          InputDecoration(
                                                        hintText: 'дд.мм.гг',
                                                        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 (value!.isEmpty) {
                                                          return S
                                                              .of(context)
                                                              .validationForEmpty;
                                                        } else {
                                                          return null;
                                                        }
                                                      },
                                                    ),
                                                  ),
                                                ),
                                              ),
                                            ),
                                          ],
                                        ),
                                        Text(
                                          "${S.of(context).type_of_tinting}",
                                          style: AppStyle.textStyle().copyWith(
                                              color: Color(0xFF959595),
                                              fontSize: 15.0,
                                              fontWeight: FontWeight.normal),
                                        ),
                                        Container(
                                          height: 10.0.h,
                                          constraints: BoxConstraints(
                                              maxHeight: 60.0, minHeight: 30.0),
                                          padding: EdgeInsets.symmetric(
                                              horizontal: 15.0),
                                          margin: EdgeInsets.symmetric(
                                              vertical: 6.0),
                                          decoration: BoxDecoration(
                                            borderRadius:
                                                BorderRadius.circular(12.0),
                                            color: Color(0xffEFEFEF),
                                          ),
                                          child: Center(
                                            child: DropdownButton(
                                              isExpanded: true,
                                              underline: SizedBox(),
                                              items: TintingPage.types!
                                                  .map((String value) {
                                                return DropdownMenuItem<String>(
                                                  value: value,
                                                  child: Text(
                                                    value,
                                                    style: AppStyle.textStyle()
                                                        .copyWith(
                                                      color: AppColors
                                                          .unSelectedColor,
                                                      fontSize: 17.0,
                                                      fontWeight:
                                                          FontWeight.normal,
                                                    ),
                                                  ),
                                                );
                                              }).toList(),
                                              onChanged: (String? value) {
                                                setState(() {
                                                  typesValue = value!;
                                                  AddTintingModel.kind =
                                                      typesToSend[TintingPage
                                                          .types!
                                                          .indexOf(
                                                              typesValue!)];
                                                });
                                              },
                                              hint: Text(
                                                typesValue ??
                                                    '${S.of(context).type_of_tinting}',
                                                style: TextStyle(
                                                  fontSize: 17.0,
                                                  fontWeight: FontWeight.w300,
                                                ),
                                              ),
                                              // style: TextStyle(
                                              //   color: Colors.red
                                              // ),
                                            ),
                                          ),
                                        ),
                                        SizedBox(height: 10.0),
                                        Row(
                                          children: [
                                            Expanded(
                                              flex: 1,
                                              child: Text(
                                                "${S.of(context).series}",
                                                style: AppStyle.textStyle()
                                                    .copyWith(
                                                        color:
                                                            Color(0xFF959595),
                                                        fontSize: 15.0,
                                                        fontWeight:
                                                            FontWeight.normal),
                                              ),
                                            ),
                                            SizedBox(width: 15.0),
                                            Expanded(
                                              flex: 2,
                                              child: Text(
                                                "${S.of(context).number}",
                                                style: AppStyle.textStyle()
                                                    .copyWith(
                                                        color:
                                                            Color(0xFF959595),
                                                        fontSize: 15.0,
                                                        fontWeight:
                                                            FontWeight.normal),
                                              ),
                                            ),
                                          ],
                                        ),
                                        Row(
                                          children: [
                                            Expanded(
                                              flex: 1,
                                              child: Container(
                                                // height: 50.0,
                                                margin: EdgeInsets.symmetric(
                                                    vertical: 1.0.w),
                                                child: TextFormField(
                                                  cursorColor:
                                                      AppColors.selectedColor,
                                                  controller: series,
                                                  inputFormatters: [
                                                    CustomTextInputFormatter(3),
                                                    FilteringTextInputFormatter
                                                        .allow(
                                                            RegExp("[a-zA-Z]")),
                                                    UpperCaseTextFormatter(),
                                                  ],
                                                  keyboardType:
                                                      TextInputType.text,
                                                  decoration: InputDecoration(
                                                    hintText: 'AAA',
                                                    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 (value!.length < 2) {
                                                      return S
                                                          .of(context)
                                                          .validationForEmpty;
                                                    } else {
                                                      return null;
                                                    }
                                                  },
                                                ),
                                              ),
                                            ),
                                            SizedBox(width: 15.0),
                                            Expanded(
                                              flex: 2,
                                              child: Container(
                                                // height: 50.0,
                                                margin: EdgeInsets.symmetric(
                                                    vertical: 1.0.w),
                                                child: TextFormField(
                                                  cursorColor:
                                                      AppColors.selectedColor,
                                                  controller: number,
                                                  inputFormatters: [
                                                    CustomTextInputFormatter(
                                                        13),
                                                    FilteringTextInputFormatter
                                                        .allow(RegExp("[0-9]")),
                                                  ],
                                                  keyboardType:
                                                      TextInputType.number,
                                                  decoration: InputDecoration(
                                                    hintText: '0123456789012',
                                                    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 (value!.length < 6) {
                                                      return S
                                                          .of(context)
                                                          .validationForMinimumNumber(
                                                              6);
                                                    } else {
                                                      return null;
                                                    }
                                                  },
                                                ),
                                              ),
                                            ),
                                          ],
                                        ),
                                      ],
                                    ),
                                  ),
                                  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: () async {
                                                AddTintingModel.number =
                                                    number.text;
                                                AddTintingModel.series =
                                                    series.text;
                                                if (AddTintingModel.kind ==
                                                    '') {
                                                  if (widget.tinting != null) {
                                                    AddTintingModel.kind =
                                                        widget.tinting!.kind;
                                                  }
                                                }
                                                if (AddTintingModel.dateEnd ==
                                                    '') {
                                                  if (widget.tinting != null) {
                                                    AddTintingModel.dateEnd =
                                                        DateFormat('yyyy-MM-dd')
                                                            .format(DateTime
                                                                .parse(widget
                                                                    .tinting!
                                                                    .dateEnd));
                                                  }
                                                }
                                                if (AddTintingModel
                                                        .datePassed ==
                                                    '') {
                                                  if (widget.tinting != null) {
                                                    AddTintingModel
                                                        .datePassed = DateFormat(
                                                            'yyyy-MM-dd')
                                                        .format(DateTime.parse(
                                                            widget.tinting!
                                                                .datePassed));
                                                  }
                                                }
                                                setState(() {
                                                  loading = true;
                                                });
                                                if (_key.currentState!
                                                    .validate()) {
                                                  _carsBloc.add(EditCarTinting(
                                                      MyCarPage.currentId!));
                                                } else {
                                                  setState(() {
                                                    loading = false;
                                                  });
                                                }
                                              },
                                              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.tinting != 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: TintingPage(
                        tinting: widget.tinting,
                      )),
                    );
                  },
                );
        });
  }
}
