import 'dart:async';
import 'dart:developer';
import 'package:flutter/material.dart';
import 'package:mc_common_app/classes/consts.dart';
import 'package:mc_common_app/extensions/int_extensions.dart';
import 'package:mc_common_app/extensions/string_extensions.dart';
import 'package:mc_common_app/generated/locale_keys.g.dart';
import 'package:mc_common_app/main.dart';
import 'package:mc_common_app/models/general_models/widgets_models.dart';
import 'package:mc_common_app/theme/colors.dart';
import 'package:mc_common_app/utils/enums.dart';
import 'package:mc_common_app/utils/utils.dart';
import 'package:mc_common_app/view_models/requests_view_model.dart';
import 'package:mc_common_app/widgets/button/show_fill_button.dart';
import 'package:mc_common_app/widgets/common_widgets/app_bar.dart';
import 'package:mc_common_app/widgets/common_widgets/search_entity_widget.dart';
import 'package:mc_common_app/widgets/dropdown/dropdow_field.dart';
import 'package:mc_common_app/widgets/extensions/extensions_widget.dart';
import 'package:mc_common_app/widgets/txt_field.dart';
import 'package:provider/provider.dart';
import 'package:easy_localization/easy_localization.dart';

class RequestsFilterView extends StatefulWidget {
  const RequestsFilterView({super.key});

  @override
  State<RequestsFilterView> createState() => _RequestsFilterViewState();
}

class _RequestsFilterViewState extends State<RequestsFilterView> {
  late RequestsVM requestsVM;

  @override
  void initState() {
    requestsVM = context.read<RequestsVM>();
    scheduleMicrotask(() async {
      await requestsVM.populateDataForRequestsFilter();
    });
    super.initState();
  }

  @override
  void dispose() {
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: CustomAppBar(
        title: LocaleKeys.requestsFilter.tr(),
        profileImageUrl: MyAssets.bnCar,
        isRemoveBackButton: false,
        isDrawerEnabled: false,
        onBackButtonTapped: () {
          // context.read<RequestsVM>().resetValues();
          Navigator.pop(context);
        },
      ),
      body: Consumer<RequestsVM>(
        builder: (BuildContext context, RequestsVM requestVM, Widget? child) {
          if (requestVM.state == ViewState.busy) {
            return const Center(
              child: CircularProgressIndicator(),
            );
          }
          return WillPopScope(
            onWillPop: () async {
              requestVM.clearRequestFilterSelections();
              return true;
            },
            child: Column(
              children: [
                ListView(
                  children: [
                    20.height,
                    // SearchEntityWidget(
                    //   title: LocaleKeys.searchByRequestType.tr(),
                    //   actionWidget: Builder(builder: (context) {
                    //     List<DropValue> requestTypeDrop = [];
                    //     for (var element in requestsVM.myRequestsTypeEnum) {
                    //       requestTypeDrop.add(DropValue(element.id.toInt(), element.enumValueStr, ""));
                    //     }
                    //     return DropdownField(
                    //       (DropValue value) => requestsVM.updateSelectionRequestTypeId(SelectionModel(selectedId: value.id, selectedOption: value.value), shouldCallVehicleTypes: false, isForSearch: true),
                    //       list: requestTypeDrop,
                    //       dropdownValue: requestsVM.requestTypeId.selectedId != -1 ? DropValue(requestsVM.requestTypeId.selectedId, requestsVM.requestTypeId.selectedOption, "") : null,
                    //       hint: LocaleKeys.selectRequestType.tr(),
                    //       errorValue: requestsVM.requestTypeId.errorValue,
                    //     );
                    //   }),
                    //   historyContent: const [],
                    //   // This is commented out because in the document it is only single value search not with the list value search. May be we can do that in future
                    //   onHistoryItemDeleted: (index) => requestVM.removeRequestTypeSearchHistory(index: index),
                    //   onHistoryItemTapped: (DropValue value) => null,
                    // ),
                    // const Divider(thickness: 1.2).paddingOnly(top: 7, bottom: 7),
                    SearchEntityWidget(
                      title: LocaleKeys.searchByRequestStatus.tr(),
                      actionWidget: Builder(builder: (context) {
                        List<DropValue> requestTypeDrop = [];
                        for (var element in requestsVM.requestStatusesEnum) {
                          requestTypeDrop.add(DropValue(element.enumValue.toInt(), element.enumValueStr, ""));
                        }
                        return DropdownField(
                          (DropValue value) => requestsVM.updateRequestStatusId(SelectionModel(selectedId: value.id, selectedOption: value.value), isForSearch: true),
                          list: requestTypeDrop,
                          dropdownValue: requestsVM.requestStatusId.selectedId != -1 ? DropValue(requestsVM.requestStatusId.selectedId, requestsVM.requestStatusId.selectedOption, "") : null,
                          hint: LocaleKeys.selectRequestStatus.tr(),
                          errorValue: requestsVM.requestStatusId.errorValue,
                        );
                      }),
                      historyContent: const [],
                      onHistoryItemDeleted: (index) => requestVM.removeRequestStatusesSearchHistory(index: index),
                      onHistoryItemTapped: (DropValue value) => null,
                    ),
                    const Divider(thickness: 1.2).paddingOnly(top: 7, bottom: 7),
                    SearchEntityWidget(
                      title: LocaleKeys.searchByCity.tr(),
                      actionWidget: Builder(builder: (context) {
                        List<DropValue> vehicleBrandsDrop = [];
                        for (var element in requestVM.vehicleCities) {
                          vehicleBrandsDrop.add(DropValue(element.id?.toInt() ?? 0, element.cityName ?? "", ""));
                        }
                        return DropdownField(
                          (DropValue value) => requestVM.updateSelectionVehicleCityId(SelectionModel(selectedId: value.id, selectedOption: value.value), isForSearch: true),
                          list: vehicleBrandsDrop,
                          dropdownValue: requestVM.vehicleCityId.selectedId != -1 ? DropValue(requestVM.vehicleCityId.selectedId, requestVM.vehicleCityId.selectedOption, "") : null,
                          hint: LocaleKeys.selectCity.tr(),
                          errorValue: requestVM.vehicleCityId.errorValue,
                        );
                      }),
                      historyContent: const [],
                      onHistoryItemDeleted: (index) => requestVM.removeVehicleLocationAdSearchHistory(index: index),
                      onHistoryItemTapped: (DropValue value) => null,
                    ),
                    const Divider(thickness: 1.2).paddingOnly(top: 7, bottom: 7),
                    SearchEntityWidget(
                      title: LocaleKeys.searchByBrandName.tr(),
                      actionWidget: TxtField(
                        hint: LocaleKeys.brand.tr(),
                        value: requestsVM.brandForSearch,
                        onChanged: (e) => requestsVM.updateBrandForSearch(e),
                      ),
                      historyContent: const [],
                      onHistoryItemDeleted: (index) => requestVM.removeVehicleBrandsAdSearchHistory(index: index),
                      onHistoryItemTapped: (DropValue value) => null,
                    ),
                    const Divider(thickness: 1.2).paddingOnly(top: 7, bottom: 7),
                    SearchEntityWidget(
                      title: LocaleKeys.searchByVehicleModel.tr(),
                      actionWidget: TxtField(
                        hint: LocaleKeys.model.tr(),
                        value: requestsVM.modelForSearch,
                        onChanged: (e) => requestsVM.updateModelForSearch(e),
                      ),
                      historyContent: const [],
                      onHistoryItemDeleted: (index) => requestVM.removeVehicleBrandsAdSearchHistory(index: index),
                      onHistoryItemTapped: (DropValue value) => null,
                    ),
                    const Divider(thickness: 1.2).paddingOnly(top: 7, bottom: 7),
                    SearchEntityWidget(
                      title: LocaleKeys.searchByVehicleYear.tr(),
                      actionWidget: Builder(
                        builder: (context) {
                          List<DropValue> vehicleBrandsDrop = [];
                          for (var element in requestVM.vehicleYears) {
                            vehicleBrandsDrop.add(DropValue(element.id?.toInt() ?? 0, element.modelYear ?? "", ""));
                          }
                          return DropdownField(
                            (DropValue value) => requestVM.updateSelectionVehicleYearId(SelectionModel(selectedId: value.id, selectedOption: value.value), isForSearch: true),
                            list: vehicleBrandsDrop,
                            dropdownValue: requestVM.vehicleYearId.selectedId != -1 ? DropValue(requestVM.vehicleYearId.selectedId, requestVM.vehicleYearId.selectedOption, "") : null,
                            hint: LocaleKeys.selectYear.tr(),
                            errorValue: requestVM.vehicleYearId.errorValue,
                          );
                        },
                      ),
                      historyContent: const [],
                      onHistoryItemDeleted: (index) => requestVM.removeVehicleYearAdSearchHistory(index: index),
                      onHistoryItemTapped: (DropValue value) => null,
                    ),
                    const Divider(thickness: 1.2).paddingOnly(top: 7, bottom: 7),
                    SearchEntityWidget(
                      title: LocaleKeys.searchByRequestedDate.tr(),
                      actionWidget: TxtField(
                        isBackgroundEnabled: true,
                        isNeedBorder: true,
                        hint: LocaleKeys.selectDate.tr(),
                        value: requestVM.requestedDateFilter,
                        isNeedClickAll: true,
                        postFixDataColor: MyColors.darkTextColor,
                        onTap: () async {
                          final formattedDate = await Utils.pickDateFromDatePicker(context, lastDate: DateTime.now(), firstDate: DateTime(2020));
                          requestsVM.updateRequestedDate(formattedDate);
                        },
                      ),
                      historyContent: const [],
                      onHistoryItemDeleted: (index) => requestVM.removeVehicleConditionSearchHistory(index: index),
                      onHistoryItemTapped: (DropValue value) => null,
                    ),
                    const Divider(thickness: 1.2).paddingOnly(top: 7, bottom: 7),
                    SearchEntityWidget(
                      title: LocaleKeys.searchByCondition.tr(),
                      actionWidget: Builder(
                        builder: (context) {
                          List<DropValue> vehicleOwnerDrop = [];
                          for (var element in requestVM.vehicleConditionsEnum) {
                            vehicleOwnerDrop.add(DropValue(element.id.toInt(), element.enumValueStr, ""));
                          }
                          return DropdownField(
                            (DropValue value) => requestVM.updateSelectionVehicleConditionId(SelectionModel(selectedId: value.id, selectedOption: value.value), isForSearch: true),
                            list: vehicleOwnerDrop,
                            dropdownValue: requestVM.vehicleConditionId.selectedId != -1 ? DropValue(requestVM.vehicleConditionId.selectedId, requestVM.vehicleConditionId.selectedOption, "") : null,
                            hint: LocaleKeys.selectCondition.tr(),
                            errorValue: requestVM.vehicleConditionId.errorValue,
                          );
                        },
                      ),
                      historyContent: const [],
                      onHistoryItemDeleted: (index) => requestVM.removeVehicleConditionSearchHistory(index: index),
                      onHistoryItemTapped: (DropValue value) => null,
                    ),
                  ],
                ).expand(),
                Container(
                  color: MyColors.white,
                  child: Column(
                    children: [
                      5.height,
                      Row(
                        children: [
                          Expanded(
                            child: ShowFillButton(
                              maxHeight: 55,
                              title: LocaleKeys.search.tr(),
                              onPressed: () async {
                                bool status = await requestVM.getRequestsBasedOnFilters();
                                if (status) {
                                  Navigator.pop(context);
                                }
                              },
                              backgroundColor: MyColors.darkPrimaryColor,
                              txtColor: MyColors.white,
                              fontSize: 18,
                            ),
                          )
                        ],
                      ),
                      8.height,
                      InkWell(
                        onTap: () {
                          requestsVM.clearRequestsFilters();
                        },
                        child: LocaleKeys.clearFilters.tr().toText(
                              fontSize: 14,
                              isBold: true,
                              color: MyColors.darkPrimaryColor,
                            ),
                      ),
                      10.height,
                    ],
                  ),
                ),
              ],
            ).horPaddingMain(),
          );
        },
      ),
    );
  }
}
