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/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/ad_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 AdsFilterView extends StatefulWidget {
  const AdsFilterView({super.key});

  @override
  State<AdsFilterView> createState() => _AdsFilterViewState();
}

class _AdsFilterViewState extends State<AdsFilterView> {
  late AdVM adVM;

  @override
  void initState() {
    adVM = context.read<AdVM>();
    scheduleMicrotask(() async {
      await adVM.populateDataForAdFilter();
    });
    super.initState();
  }

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

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: CustomAppBar(
        title: LocaleKeys.adsFilter.tr(),
        profileImageUrl: MyAssets.bnCar,
        isRemoveBackButton: false,
        isDrawerEnabled: false,
        onBackButtonTapped: () {
          context.read<AdVM>().resetValues();
          Navigator.pop(context);
        },
      ),
      body: Consumer<AdVM>(
        builder: (BuildContext context, AdVM adVM, Widget? child) {
          if (adVM.state == ViewState.busy) {
            return const Center(
              child: CircularProgressIndicator(),
            );
          }
          return WillPopScope(
            onWillPop: () async {
              adVM.clearAdFilterSelections();
              return true;
            },
            child: Column(
              children: [
                ListView(
                  children: [
                    20.height,
                    SearchEntityWidget(
                      title: LocaleKeys.searchByCity.tr(),
                      actionWidget: Builder(builder: (context) {
                        List<DropValue> vehicleBrandsDrop = [];
                        for (var element in adVM.vehicleCities) {
                          vehicleBrandsDrop.add(DropValue(element.id?.toInt() ?? 0, element.cityName ?? "", ""));
                        }
                        return DropdownField(
                          (DropValue value) => adVM.updateSelectionVehicleCityId(SelectionModel(selectedId: value.id, selectedOption: value.value), isForSearch: true),
                          list: vehicleBrandsDrop,
                          dropdownValue: adVM.vehicleCityId.selectedId != -1 ? DropValue(adVM.vehicleCityId.selectedId, adVM.vehicleCityId.selectedOption, "") : null,
                          hint: LocaleKeys.selectCity.tr(),
                          errorValue: adVM.vehicleCityId.errorValue,
                        );
                      }),
                      historyContent: adVM.vehicleLocationAdSearchHistory,
                      onHistoryItemDeleted: (index) => adVM.removeVehicleLocationAdSearchHistory(index: index),
                      onHistoryItemTapped: (DropValue value) => null,
                    ),
                    const Divider(thickness: 1.2).paddingOnly(top: 7, bottom: 7),
                    SearchEntityWidget(
                      title: LocaleKeys.searchByBrandName.tr(),
                      actionWidget: Builder(builder: (context) {
                        List<DropValue> vehicleBrandsDrop = [];
                        for (var element in adVM.vehicleBrands) {
                          vehicleBrandsDrop.add(DropValue(element.id?.toInt() ?? 0, element.vehicleBrandDescription ?? "", ""));
                        }
                        return DropdownField(
                          (DropValue value) => adVM.updateSelectionVehicleBrandId(SelectionModel(selectedId: value.id, selectedOption: value.value), isForSearch: true),
                          list: vehicleBrandsDrop,
                          dropdownValue: adVM.vehicleBrandId.selectedId != -1 ? DropValue(adVM.vehicleBrandId.selectedId, adVM.vehicleBrandId.selectedOption, "") : null,
                          hint: LocaleKeys.selectVehicleBrand.tr(),
                          errorValue: adVM.vehicleBrandId.errorValue,
                        );
                      }),
                      historyContent: adVM.vehicleBrandsAdSearchHistory,
                      onHistoryItemDeleted: (index) => adVM.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 adVM.vehicleModelYears) {
                            vehicleBrandsDrop.add(DropValue(element.id?.toInt() ?? 0, element.modelYear ?? "", ""));
                          }
                          return DropdownField(
                            (DropValue value) => adVM.updateSelectionVehicleModelYearId(SelectionModel(selectedId: value.id, selectedOption: value.value), isForSearch: true),
                            list: vehicleBrandsDrop,
                            dropdownValue: adVM.vehicleModelYearId.selectedId != -1 ? DropValue(adVM.vehicleModelYearId.selectedId, adVM.vehicleModelYearId.selectedOption, "") : null,
                            hint: LocaleKeys.selectYear.tr(),
                            errorValue: adVM.vehicleModelYearId.errorValue,
                          );
                        },
                      ),
                      historyContent: adVM.vehicleYearAdSearchHistory,
                      onHistoryItemDeleted: (index) => adVM.removeVehicleYearAdSearchHistory(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 adVM.vehicleConditionsEnum) {
                            vehicleOwnerDrop.add(DropValue(element.id.toInt(), element.enumValueStr, ""));
                          }
                          return DropdownField(
                            (DropValue value) =>
                                adVM.updateSelectionVehicleConditionId(SelectionModel(selectedId: value.id, selectedOption: value.value), isForSearch: true, showSelectionInDropdown: false),
                            list: vehicleOwnerDrop,
                            dropdownValue: adVM.vehicleConditionId.selectedId != -1 ? DropValue(adVM.vehicleConditionId.selectedId, adVM.vehicleConditionId.selectedOption, "") : null,
                            hint: LocaleKeys.selectCondition.tr(),
                            errorValue: adVM.vehicleConditionId.errorValue,
                          );
                        },
                      ),
                      historyContent: adVM.vehicleAdConditionSearchHistory,
                      onHistoryItemDeleted: (index) => adVM.removeVehicleAdConditionSearchHistory(index: index),
                      onHistoryItemTapped: (DropValue value) => null,
                    ),
                    const Divider(thickness: 1.2).paddingOnly(top: 7, bottom: 7),
                    SearchEntityWidget(
                      title: LocaleKeys.searchByCreatedDate.tr(),
                      actionWidget: TxtField(
                        isNeedBorder: true,
                        hint: LocaleKeys.createdOn.tr(),
                        value: adVM.vehicleAdDurationId.selectedOption,
                        isNeedClickAll: true,
                        postFixDataColor: MyColors.darkTextColor,
                        onTap: () async {
                          final formattedDate = await Utils.pickDateFromDatePicker(context, firstDate: DateTime(2020), lastDate: DateTime.now());
                          if (formattedDate.isEmpty) {
                            return;
                          }
                          adVM.updateSelectionDurationStartDate(formattedDate);
                          DropValue value = DropValue(0, formattedDate, "");
                          adVM.addToVehicleAdCreatedDateSearchHistory(value: value);
                        },
                      ),
                      historyContent: adVM.vehicleAdCreatedDateSearchHistory,
                      onHistoryItemDeleted: (index) => adVM.removeVehicleAdCreatedDateSearchHistory(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: () {
                                Navigator.pop(context);
                                adVM.getAdsBasedOnFilters();
                              },
                              backgroundColor: MyColors.darkPrimaryColor,
                              txtColor: MyColors.white,
                              fontSize: 18,
                            ),
                          )
                        ],
                      ),
                      8.height,
                      InkWell(
                        onTap: () => adVM.clearAdsFilters(),
                        child: LocaleKeys.clearFilters.tr().toText(
                              fontSize: 14,
                              isBold: true,
                              color: MyColors.darkPrimaryColor,
                            ),
                      ),
                      10.height,
                    ],
                  ),
                ),
              ],
            ).horPaddingMain(),
          );
        },
      ),
    );
  }
}
