import 'package:flutter/gestures.dart';
import 'package:mc_common_app/classes/app_state.dart';
import 'package:mc_common_app/classes/consts.dart';
import 'package:mc_common_app/config/routes.dart';
import 'package:mc_common_app/generated/locale_keys.g.dart';
import 'package:mc_common_app/models/requests_models/request_model.dart';
import 'package:mc_common_app/utils/dialogs_and_bottomsheets.dart';
import 'package:mc_common_app/utils/navigator.dart';
import 'package:mc_common_app/view_models/requests_view_model.dart';
import 'package:flutter/material.dart';
import 'package:mc_common_app/extensions/int_extensions.dart';
import 'package:mc_common_app/extensions/string_extensions.dart';
import 'package:mc_common_app/theme/colors.dart';
import 'package:mc_common_app/utils/enums.dart';
import 'package:mc_common_app/views/requests/widget/request_item.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';
import 'package:easy_localization/easy_localization.dart';

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

  void cancelRequestBottomSheet(BuildContext context, int requestId) {
    return actionConfirmationBottomSheet(
      context: context,
      title: LocaleKeys.cancelRequestPrompt.tr().toText(fontSize: 28, isBold: true, letterSpacing: -1.44),
      subtitle: LocaleKeys.requestPermanentlyCancelled.tr(),
      actionButtonYes: Expanded(
        child: ShowFillButton(
          maxHeight: 55,
          title: LocaleKeys.yes.tr(),
          fontSize: 15,
          onPressed: () async {
            Navigator.pop(context);

            final requestVM = context.read<RequestsVM>();

            bool status = await requestVM.onActionRequestTapped(context: context, requestStatusEnum: RequestStatusEnum.cancelled, requestId: requestId);
            if (status) {
              await requestVM.getRequests(isNeedToRebuild: true);
            }
          },
        ),
      ),
      actionButtonNo: Expanded(
        child: ShowFillButton(
          maxHeight: 55,
          isFilled: false,
          borderColor: MyColors.darkPrimaryColor,
          title: LocaleKeys.no.tr(),
          txtColor: MyColors.darkPrimaryColor,
          fontSize: 15,
          onPressed: () {
            Navigator.pop(context);
          },
        ),
      ),
    );
  }

  bool shouldDismiss(RequestStatusEnum requestStatusEnum) {
    if (AppState().currentAppType == AppType.provider) {
      return false;
    }

    if (requestStatusEnum == RequestStatusEnum.pending || requestStatusEnum == RequestStatusEnum.submitted) {
      return true;
    }
    return false;
  }

  @override
  Widget build(BuildContext context) {
    return Consumer(builder: (BuildContext context, RequestsVM requestsVM, Widget? child) {
      return Scaffold(
        appBar: CustomAppBar(
          title: LocaleKeys.manageRequests.tr(),
          isRemoveBackButton: true,
          actions: [
            Padding(
              padding: EdgeInsets.only(top: requestsVM.requestsFiltersCounter > 0 ? 20 : 0, right: 21),
              child: Badge(
                isLabelVisible: requestsVM.requestsFiltersCounter > 0,
                largeSize: 15,
                smallSize: 20,
                backgroundColor: MyColors.darkPrimaryColor,
                label: Text('${requestsVM.requestsFiltersCounter}'),
                child: MyAssets.searchIcon.buildSvg(),
              ),
            ).onPress(() {
              navigateWithName(context, AppRoutes.requestsFilterView);
            })
          ],
        ),
        body: Container(
          color: MyColors.backgroundColor,
          width: double.infinity,
          height: double.infinity,
          child: Column(
            children: [
              16.height,
              FiltersList(
                filterList: requestsVM.requestsTypeFilterOptions,
                onFilterTapped: (index, selectedFilterId) {
                  requestsVM.applyFilterOnRequestsVM(requestsTypeEnum: selectedFilterId.toRequestTypeEnum());
                },
              ),
              8.height,
              Expanded(
                  child: RefreshIndicator(
                onRefresh: () async => await requestsVM.getRequestsBasedOnFilters(),
                child: requestsVM.state == ViewState.busy
                    ? const Center(child: CircularProgressIndicator())
                    : requestsVM.myFilteredRequests.isEmpty
                        ? Column(
                            mainAxisAlignment: MainAxisAlignment.center,
                            children: [
                              LocaleKeys.noRequeststoShow.tr().toText(fontSize: 16, color: MyColors.lightTextColor),
                              if (requestsVM.requestsFiltersCounter > 0) ...[
                                8.height,
                                InkWell(
                                  onTap: () async {
                                    requestsVM.clearRequestsFilters();
                                    await requestsVM.getRequestsBasedOnFilters();
                                  },
                                  child: LocaleKeys.clearFilters.tr().toText(
                                        fontSize: 14,
                                        isBold: true,
                                        color: MyColors.darkPrimaryColor,
                                      ),
                                ),
                              ],
                            ],
                          )
                        : ListView.separated(
                            itemBuilder: (context, index) {
                              return Dismissible(
                                key: Key(index.toString()),
                                background: const SizedBox(),
                                secondaryBackground: Container(
                                  color: const Color(0xFFDD0505),
                                  child: Row(
                                    crossAxisAlignment: CrossAxisAlignment.center,
                                    mainAxisAlignment: MainAxisAlignment.end,
                                    children: [
                                      LocaleKeys.cancel.tr().toText(fontSize: 15, fontWeight: MyFonts.Medium, height: 23 / 25, color: MyColors.white).margin(right: 23),
                                    ],
                                  ),
                                ),
                                dragStartBehavior: DragStartBehavior.start,
                                direction: shouldDismiss(requestsVM.myFilteredRequests[index].requestStatus) ? DismissDirection.endToStart : DismissDirection.none,
                                confirmDismiss: (DismissDirection direction) async {
                                  cancelRequestBottomSheet(context, requestsVM.myFilteredRequests[index].id);
                                  return;
                                },
                                child: RequestItem(
                                    request: requestsVM.myFilteredRequests[index],
                                    shouldShowStatuses: AppState().currentAppType == AppType.customer,
                                    onTap: () async {
                                      RequestModel request = requestsVM.myFilteredRequests[index];
                                      requestsVM.updateCurrentSelectedRequest(request);
                                      if (request.requestStatus == RequestStatusEnum.pending ||
                                          request.requestStatus == RequestStatusEnum.cancelled ||
                                          request.requestStatus == RequestStatusEnum.expired) {
                                        return;
                                      }
                                      if (AppState().currentAppType == AppType.provider) {
                                        RequestDetailPageArguments requestDetailPageArguments = RequestDetailPageArguments(requestIndex: index, requestModel: request);
                                        navigateWithName(context, AppRoutes.requestsDetailPage, arguments: requestDetailPageArguments);
                                      } else {
                                        requestsVM.myFilteredRequests[index].offerCount = 0;
                                        requestsVM.notifyListeners();
                                        navigateWithName(context, AppRoutes.offersListPage, arguments: request.id);
                                      }
                                    }),
                              );
                            },
                            separatorBuilder: (context, index) {
                              return 16.height;
                            },
                            itemCount: requestsVM.myFilteredRequests.length,
                            padding: const EdgeInsets.only(left: 16, right: 16, bottom: 16, top: 8),
                          ),
              ))
            ],
          ),
        ),
        floatingActionButton: AppState().currentAppType == AppType.customer
            ? FloatingActionButton(
                onPressed: () => navigateWithName(context, AppRoutes.createRequestPage),
                backgroundColor: MyColors.darkPrimaryColor,
                child: const Icon(
                  Icons.add,
                  color: MyColors.white,
                ),
              )
            : null,
      );
    });
  }
}
