import 'dart:async';

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

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

  @override
  State<AppointmentsFilterView> createState() => _AppointmentsFilterViewState();
}

class _AppointmentsFilterViewState extends State<AppointmentsFilterView> {
  late AppointmentsVM appointmentsVM;

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

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

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: CustomAppBar(
        title: LocaleKeys.appointmentsFilter.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.updateAppointmentFilterSelectedProviderId(SelectionModel(selectedId: value.id, selectedOption: value.value), isForSearch: true),
                            list: appointmentsVM.providersDropList,
                            dropdownValue: appointmentsVM.appointmentFilterSelectedProviderId.selectedId != -1
                                ? DropValue(appointmentsVM.appointmentFilterSelectedProviderId.selectedId, appointmentsVM.appointmentFilterSelectedProviderId.selectedOption, "")
                                : null,
                            hint: LocaleKeys.selectProvider.tr(),
                          );
                        },
                      ),
                      historyContent: appointmentsVM.appointmentFilterProviderSearchHistory,
                      onHistoryItemDeleted: (index) {
                        appointmentsVM.removeAppointmentFilterProviderSearchHistory(index: index);
                      },
                      onHistoryItemTapped: (DropValue value) =>
                          appointmentsVM.updateAppointmentFilterSelectedProviderId(SelectionModel(selectedId: value.id, selectedOption: value.value), isForSearch: true),
                    ),
                    if (appointmentsVM.state == ViewState.busy) ...[
                      Row(
                        mainAxisAlignment: MainAxisAlignment.center,
                        children: [
                          SizedBox(
                            height: 5.h,
                            width: 5.h,
                            child: const CircularProgressIndicator(),
                          ),
                        ],
                      ),
                    ],
                    if (appointmentsVM.appointmentFilterProviderSearchHistory.isNotEmpty) ...[
                      const Divider(thickness: 1.2).paddingOnly(top: 5, bottom: 5),
                      SearchEntityWidget(
                        title: LocaleKeys.searchByBranch.tr(),
                        actionWidget: Builder(
                          builder: (context) {
                            return DropdownField(
                              (DropValue value) => appointmentsVM.updateAppointmentFilterSelectedBranchId(SelectionModel(selectedId: value.id, selectedOption: value.value), isForSearch: true),
                              list: appointmentsVM.branchesDropList,
                              dropdownValue: appointmentsVM.appointmentFilterSelectedBranchId.selectedId != -1
                                  ? DropValue(appointmentsVM.appointmentFilterSelectedBranchId.selectedId, appointmentsVM.appointmentFilterSelectedBranchId.selectedOption, "")
                                  : null,
                              hint: LocaleKeys.selectBranch.tr(),
                            );
                          },
                        ),
                        historyContent: appointmentsVM.appointmentFilterBranchSearchHistory,
                        onHistoryItemDeleted: (index) {
                          appointmentsVM.removeAppointmentFilterBranchSearchHistory(index: index);
                        },
                        onHistoryItemTapped: (DropValue value) =>
                            appointmentsVM.updateAppointmentFilterSelectedBranchId(SelectionModel(selectedId: value.id, selectedOption: value.value), isForSearch: 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.updateAppointmentFilterSelectedCategoryId(SelectionModel(selectedId: value.id, selectedOption: value.value), isForSearch: true),
                            list: appointmentsVM.categoryDropList,
                            dropdownValue: appointmentsVM.appointmentFilterSelectedCategoryId.selectedId != -1
                                ? DropValue(appointmentsVM.appointmentFilterSelectedCategoryId.selectedId, appointmentsVM.appointmentFilterSelectedCategoryId.selectedOption, "")
                                : null,
                            hint: LocaleKeys.selectCategory.tr(),
                          );
                        },
                      ),
                      historyContent: appointmentsVM.appointmentFilterCategorySearchHistory,
                      onHistoryItemDeleted: (index) {
                        appointmentsVM.removeAppointmentFilterCategorySearchHistory(index: index);
                      },
                      onHistoryItemTapped: (DropValue value) =>
                          appointmentsVM.updateAppointmentFilterSelectedCategoryId(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.updateAppointmentFilterSelectedServiceId(SelectionModel(selectedId: value.id, selectedOption: value.value), isForSearch: true),
                          list: appointmentsVM.servicesDropList,
                          dropdownValue: appointmentsVM.appointmentFilterSelectedServiceId.selectedId != -1
                              ? DropValue(appointmentsVM.appointmentFilterSelectedServiceId.selectedId, appointmentsVM.appointmentFilterSelectedServiceId.selectedOption, "")
                              : null,
                          hint: LocaleKeys.selectServices.tr(),
                        );
                      }),
                      historyContent: appointmentsVM.appointmentFilterServicesSearchHistory,
                      onHistoryItemDeleted: (index) => appointmentsVM.removeAppointmentFilterServicesSearchHistory(index: index),
                      onHistoryItemTapped: (DropValue value) => null,
                    ),
                    const Divider(thickness: 1.2).paddingOnly(top: 5, bottom: 5),
                    SearchEntityWidget(
                      title: LocaleKeys.searchByItem.tr(),
                      actionWidget: Builder(builder: (context) {
                        return DropdownField(
                          (DropValue value) => appointmentsVM.updateAppointmentFilterSelectedItemId(SelectionModel(selectedId: value.id, selectedOption: value.value), isForSearch: true),
                          list: appointmentsVM.itemsDropList,
                          dropdownValue: appointmentsVM.appointmentFilterSelectedItemId.selectedId != -1
                              ? DropValue(appointmentsVM.appointmentFilterSelectedItemId.selectedId, appointmentsVM.appointmentFilterSelectedItemId.selectedOption, "")
                              : null,
                          hint: LocaleKeys.selectItems.tr(),
                        );
                      }),
                      historyContent: appointmentsVM.appointmentFilterItemsSearchHistory,
                      onHistoryItemDeleted: (index) => appointmentsVM.removeAppointmentFilterItemsSearchHistory(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);
                                appointmentsVM.getAppointmentsBasedOnFilters();
                              },
                              backgroundColor: MyColors.darkPrimaryColor,
                              txtColor: MyColors.white,
                              fontSize: 18,
                            ),
                          )
                        ],
                      ),
                      8.height,
                      InkWell(
                        onTap: () => appointmentsVM.clearAppointmentFilters(),
                        child: LocaleKeys.clearFilters.tr().toText(
                              fontSize: 14,
                              isBold: true,
                              color: MyColors.darkPrimaryColor,
                            ),
                      ),
                      10.height,
                    ],
                  ),
                ),
              ],
            ).horPaddingMain(),
          );
        },
      ),
    );
  }
}
