import 'dart:async';

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/view_models/ad_view_model.dart';
import 'package:mc_common_app/view_models/appointments_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/common_widgets/slider_widget.dart';
import 'package:mc_common_app/widgets/dropdown/dropdow_field.dart';
import 'package:mc_common_app/widgets/extensions/extensions_widget.dart';
import 'package:provider/provider.dart';
import 'package:easy_localization/easy_localization.dart';

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

  @override
  State<BranchesFilterView> createState() => _BranchesFilterViewState();
}

class _BranchesFilterViewState extends State<BranchesFilterView> {
  late AppointmentsVM appointmentsVM;

  @override
  void initState() {
    appointmentsVM = context.read<AppointmentsVM>();
    scheduleMicrotask(() async {
      await appointmentsVM.populateDataForBranchesFilter();
    });
    super.initState();
  }

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

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: CustomAppBar(
        title: LocaleKeys.branchesFilter.tr(),
        profileImageUrl: MyAssets.bnCar,
        isRemoveBackButton: false,
        isDrawerEnabled: false,
        onBackButtonTapped: () {
          context.read<AdVM>().resetValues();
          Navigator.pop(context);
        },
      ),
      body: Consumer<AppointmentsVM>(
        builder: (BuildContext context, AppointmentsVM appointmentsVM,
            Widget? child) {
          return WillPopScope(
            onWillPop: () async {
              context.read<AdVM>().resetValues();
              return true;
            },
            child: Column(
              children: [
                ListView(
                  children: [
                    20.height,
                    SearchEntityWidget(
                      title: LocaleKeys.searchByProvider.tr(),
                      actionWidget: Builder(
                        builder: (context) {
                          return DropdownField(
                            (DropValue value) => appointmentsVM
                                .updateBranchFilterSelectedProviderId(
                                    SelectionModel(
                                        selectedId: value.id,
                                        selectedOption: value.value),
                                    isForSearch: true),
                            list: appointmentsVM.providersDropList,
                            dropdownValue: appointmentsVM
                                        .branchFilterSelectedProviderId
                                        .selectedId !=
                                    -1
                                ? DropValue(
                                    appointmentsVM
                                        .branchFilterSelectedProviderId
                                        .selectedId,
                                    appointmentsVM
                                        .branchFilterSelectedProviderId
                                        .selectedOption,
                                    "")
                                : null,
                            hint: LocaleKeys.selectProvider.tr(),
                          );
                        },
                      ),
                      historyContent:
                          appointmentsVM.branchFilterProviderSearchHistory,
                      onHistoryItemDeleted: (index) {
                        appointmentsVM.removeBranchFilterProviderSearchHistory(
                            index: index);
                      },
                      onHistoryItemTapped: (DropValue value) =>
                          appointmentsVM.updateBranchFilterSelectedProviderId(
                              SelectionModel(
                                  selectedId: value.id,
                                  selectedOption: value.value),
                              isForSearch: true),
                    ),
                    const Divider(thickness: 1.2)
                        .paddingOnly(top: 5, bottom: 5),
                    Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        LocaleKeys.searchByDistance
                            .tr()
                            .toText(fontSize: 16, isBold: true),
                        Row(
                          children: [
                            "0 KM".toText(fontSize: 12, isBold: true),
                            Expanded(
                              child: SliderWidget(
                                minValue: 0,
                                maxValue: 100,
                                value:
                                    appointmentsVM.branchFilterCurrentDistance,
                                onChanged: appointmentsVM
                                    .updateBranchFilterCurrentDistance,
                              ),
                            ),
                            "${appointmentsVM.branchFilterCurrentDistance.toInt()} KM"
                                .toText(fontSize: 12, isBold: true),
                          ],
                        ),
                      ],
                    ),
                    const Divider(thickness: 1.2)
                        .paddingOnly(top: 5, bottom: 5),
                    SearchEntityWidget(
                      title: LocaleKeys.searchByCategory.tr(),
                      actionWidget: Builder(
                        builder: (context) {
                          return DropdownField(
                            (DropValue value) => appointmentsVM
                                .updateBranchFilterSelectedCategoryId(
                                    SelectionModel(
                                        selectedId: value.id,
                                        selectedOption: value.value),
                                    isForSearch: true),
                            list: appointmentsVM.categoryDropList,
                            dropdownValue: appointmentsVM
                                        .branchFilterSelectedCategoryId
                                        .selectedId !=
                                    -1
                                ? DropValue(
                                    appointmentsVM
                                        .branchFilterSelectedCategoryId
                                        .selectedId,
                                    appointmentsVM
                                        .branchFilterSelectedCategoryId
                                        .selectedOption,
                                    "")
                                : null,
                            hint: LocaleKeys.selectCategory.tr(),
                          );
                        },
                      ),
                      historyContent:
                          appointmentsVM.branchFilterCategorySearchHistory,
                      onHistoryItemDeleted: (index) {
                        appointmentsVM.removeBranchFilterCategorySearchHistory(
                            index: index);
                      },
                      onHistoryItemTapped: (DropValue value) =>
                          appointmentsVM.updateBranchFilterSelectedCategoryId(
                              SelectionModel(
                                  selectedId: value.id,
                                  selectedOption: value.value),
                              isForSearch: true),
                    ),
                    const Divider(thickness: 1.2)
                        .paddingOnly(top: 5, bottom: 5),
                    SearchEntityWidget(
                      title: LocaleKeys.searchByService.tr(),
                      actionWidget: Builder(builder: (context) {
                        return DropdownField(
                          (DropValue value) => appointmentsVM
                              .updateBranchFilterSelectedServiceId(
                                  SelectionModel(
                                      selectedId: value.id,
                                      selectedOption: value.value),
                                  isForSearch: true),
                          list: appointmentsVM.servicesDropList,
                          dropdownValue: appointmentsVM
                                      .branchFilterSelectedServiceId
                                      .selectedId !=
                                  -1
                              ? DropValue(
                                  appointmentsVM
                                      .branchFilterSelectedServiceId.selectedId,
                                  appointmentsVM.branchFilterSelectedServiceId
                                      .selectedOption,
                                  "")
                              : null,
                          hint: LocaleKeys.selectService.tr(),
                        );
                      }),
                      historyContent:
                          appointmentsVM.branchFilterServicesSearchHistory,
                      onHistoryItemDeleted: (index) => appointmentsVM
                          .removeBranchFilterServicesSearchHistory(
                              index: index),
                      onHistoryItemTapped: (DropValue value) => null,
                    ),
                    const Divider(thickness: 1.2)
                        .paddingOnly(top: 5, bottom: 5),
                    Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        LocaleKeys.searchByMinimumRatings
                            .tr()
                            .toText(fontSize: 16, isBold: true),
                        Row(
                          children: [
                            "1 Star".toText(fontSize: 12, isBold: true),
                            Expanded(
                              child: SliderWidget(
                                minValue: 0,
                                maxValue: 5,
                                value: appointmentsVM.branchFilterByRating,
                                onChanged:
                                    appointmentsVM.updateBranchFilterByRating,
                              ),
                            ),
                            "${appointmentsVM.branchFilterByRating.toInt()} Star"
                                .toText(fontSize: 12, isBold: true),
                          ],
                        ),
                      ],
                    ),
                  ],
                ).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);
                                appointmentsVM.getBranchesBasedOnFilters();
                              },
                              backgroundColor: MyColors.darkPrimaryColor,
                              txtColor: MyColors.white,
                              fontSize: 18,
                            ),
                          )
                        ],
                      ),
                      8.height,
                      InkWell(
                        onTap: () => appointmentsVM.clearBranchFilters(),
                        child: LocaleKeys.clearFilters.tr().toText(
                              fontSize: 14,
                              isBold: true,
                              color: MyColors.darkPrimaryColor,
                            ),
                      ),
                      10.height,
                    ],
                  ),
                ),
              ],
            ).horPaddingMain(),
          );
        },
      ),
    );
  }
}
