import 'dart:developer';

import 'package:easy_localization/easy_localization.dart';
import 'package:flutter/material.dart';
import 'package:mc_common_app/classes/app_state.dart';
import 'package:mc_common_app/classes/consts.dart';
import 'package:mc_common_app/config/dependency_injection.dart';
import 'package:mc_common_app/config/routes.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/advertisment_models/ad_details_model.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/navigator.dart';
import 'package:mc_common_app/view_models/ad_view_model.dart';
import 'package:mc_common_app/views/advertisement/components/ads_list_widget.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/categories_list.dart';
import 'package:mc_common_app/widgets/extensions/extensions_widget.dart';
import 'package:provider/provider.dart';

class AdsFragment extends StatelessWidget {
  const AdsFragment({super.key});

  List<AdDetailsModel> getAdsList(AdVM adVM) {
    if (adVM.isExploreAdsTapped) {
      return adVM.exploreAdsFilteredList;
    }
    if (adVM.myAdsFilteredList.isNotEmpty) {
      return adVM.myAdsFilteredList;
    }
    return [];
  }

  @override
  Widget build(BuildContext context) {
    return Consumer(
      builder: (BuildContext context, AdVM adVM, Widget? child) {
        return Scaffold(
          appBar: CustomAppBar(
            title: LocaleKeys.ads.tr(),
            isRemoveBackButton: true,
            actions: [
              Padding(
                padding: EdgeInsets.only(top: adVM.adsFiltersCounter > 0 ? 20 : 0, right: 21),
                child: Badge(
                  isLabelVisible: adVM.adsFiltersCounter > 0,
                  largeSize: 15,
                  smallSize: 20,
                  backgroundColor: MyColors.darkPrimaryColor,
                  label: Text('${adVM.adsFiltersCounter}'),
                  child: MyAssets.searchIcon.buildSvg(),
                ),
              ).onPress(() {
                navigateWithName(context, AppRoutes.adsFilterView);
              })
            ],
          ),
          body: SizedBox(
            width: double.infinity,
            height: double.infinity,
            child: Column(
              children: [
                16.height,
                Consumer(
                  builder: (BuildContext context, AdVM adVM, Widget? child) {
                    return Column(
                      children: [
                        Row(
                          children: [
                            Expanded(
                              child: ShowFillButton(
                                isFilled: adVM.isExploreAdsTapped,
                                maxHeight: 55,
                                fontSize: 15,
                                title: LocaleKeys.exploreAds.tr(),
                                txtColor: adVM.isExploreAdsTapped ? MyColors.white : MyColors.darkTextColor,
                                onPressed: () {
                                  print("accessToken: ${AppState().getUser.data!.accessToken}");
                                  if (adVM.myAds.isEmpty) {
                                    adVM.getMyAds();
                                  }
                                  adVM.updateIsExploreAds(true);
                                },
                              ),
                            ),
                            12.width,
                            Expanded(
                              child: ShowFillButton(
                                isFilled: !adVM.isExploreAdsTapped,
                                txtColor: !adVM.isExploreAdsTapped ? MyColors.white : MyColors.darkTextColor,
                                maxHeight: 55,
                                fontSize: 15,
                                title: LocaleKeys.myAds.tr(),
                                onPressed: () {
                                  adVM.updateIsExploreAds(false);
                                },
                              ),
                            ),
                          ],
                        ).horPaddingMain(),
                        if (adVM.isExploreAdsTapped) ...[
                          if (adVM.adsFiltersCounter == 0) ...[
                            16.height,
                            FiltersList(
                              filterList: adVM.exploreAdsFilterOptions,
                              onFilterTapped: (index, selectedFilterId) => adVM.applyFilterOnExploreAds(createdByRoleFilter: selectedFilterId.toCreatedByRoleEnum()),
                              needLeftPadding: false,
                            ).paddingOnly(left: 21),
                          ]
                        ] else ...[
                          16.height,
                          FiltersList(
                            filterList: adVM.myAdsFilterOptions,
                            onFilterTapped: (index, selectedFilterId) => adVM.applyFilterOnMyAds(adPostStatusEnum: selectedFilterId.toAdPostEnum()),
                            needLeftPadding: false,
                          ).paddingOnly(left: 21),
                        ],
                      ],
                    );
                  },
                ),
                16.height,
                Expanded(
                  child: RefreshIndicator(
                    onRefresh: () async {
                      if (adVM.isExploreAdsTapped) {
                        CreatedByRoleEnum createdByRoleEnum = adVM.exploreAdsFilterOptions.firstWhere((element) => element.isSelected).id.toCreatedByRoleEnum();
                        adVM.applyFilterOnExploreAds(createdByRoleFilter: createdByRoleEnum);
                      } else {
                        AdPostStatus adPostStatusEnum = adVM.myAdsFilterOptions.firstWhere((element) => element.isSelected).id.toAdPostEnum();
                        adVM.applyFilterOnMyAds(adPostStatusEnum: adPostStatusEnum);
                      }
                    },
                    child: adVM.state == ViewState.busy
                        ? const Center(child: CircularProgressIndicator())
                        : AdsListWidget(
                            isAdsFragment: true,
                            shouldShowAdStatus: !adVM.isExploreAdsTapped,
                            adsList: getAdsList(adVM),
                            onFetchMoreAds: () {
                              log("fetch more ads");
                            },
                          ),
                  ),
                )
              ],
            ),
          ),
          floatingActionButton: FloatingActionButton(
            onPressed: () async {
              adVM.getVehicleAdsDuration();
              if (AppState().userType != UserType.providerDealer) {
                if (adVM.vehicleAdDurationId.selectedId == -1 && adVM.vehicleAdsDurations.isNotEmpty) {
                  SelectionModel selection = SelectionModel(
                    selectedId: adVM.vehicleAdsDurations.first.id ?? 0,
                    selectedOption: ("${adVM.vehicleAdsDurations.first.days} ${LocaleKeys.daysVar.tr()}"),
                    itemPrice: adVM.vehicleAdsDurations.first.price!.toString(),
                    currency: adVM.vehicleAdsDurations.first.currency!.toString(),
                  );
                  adVM.updateVehicleAdDurationId(selection);
                }
              }

              navigateWithName(context, AppRoutes.selectAdTypeView, arguments: [injector.get<AppState>().currentAppType == AppType.provider, false, -1]);
            },
            backgroundColor: MyColors.darkPrimaryColor,
            child: const Icon(Icons.add, color: MyColors.white),
          ),
        );
      },
    );
  }
}
