import 'dart:async';
import 'dart:developer';
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/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/general_models/widgets_models.dart';
import 'package:mc_common_app/models/shipping_models/shipping_status_model.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/utils/utils.dart';
import 'package:mc_common_app/view_models/shipping_management_view_model.dart';
import 'package:mc_common_app/widgets/button/show_fill_button.dart';
import 'package:mc_common_app/widgets/checkbox_with_title_desc.dart';
import 'package:mc_common_app/widgets/common_widgets/app_bar.dart';
import 'package:mc_common_app/widgets/common_widgets/filters_list.dart';
import 'package:mc_common_app/widgets/common_widgets/info_bottom_sheet.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 ShippingManagementView extends StatefulWidget {
  const ShippingManagementView({super.key});

  @override
  State<ShippingManagementView> createState() => _ShippingManagementViewState();
}

class _ShippingManagementViewState extends State<ShippingManagementView> {
  late ShippingManagementVM shippingViewModel;

  @override
  void initState() {
    shippingViewModel = context.read<ShippingManagementVM>();
    scheduleMicrotask(() async {
      if (shippingViewModel.shippingRequestFilterOptions.isNotEmpty) {
        await shippingViewModel.populateShippingRequestFilterList();
      }
      if (shippingViewModel.selfPickupRequestsFilterOptions.isNotEmpty) {
        await shippingViewModel.populateSelfPickupRequestFilterList();
      }
      if (shippingViewModel.isSelfPickupTapped) {
        await shippingViewModel.getSelfPickupRequestsListByFilters();
      } else {
        await shippingViewModel.getShippingRequestsListByFilters();
      }
    });
    super.initState();
  }

  List<FilterListModel> getAvailableStatusesShippingList(List<FilterListModel> list, ShippingRequestStatusEnum shippingRequestStatusEnum) {
    List<FilterListModel> newList = [];

    for (var element in list) {
      if (element.id > shippingRequestStatusEnum.getIdFromShippingStatusEnum()) {
        newList.add(element);
      }
    }
    return newList;
  }

  List<FilterListModel> getAvailableStatusesPickupList(List<FilterListModel> list, SelfPickupRequestStatusEnum selfPickupRequestStatusEnum) {
    List<FilterListModel> newList = [];

    for (var element in list) {
      if (element.id > selfPickupRequestStatusEnum.getIdFromSelfPickupStatusEnum()) {
        newList.add(element);
      }
    }
    return newList;
  }

  Future buildUpdateShippingStatusBottomSheet({required int shippingRequestId, required ShippingRequestStatusEnum shippingRequestStatusEnum}) {
    return showModalBottomSheet(
      context: context,
      isScrollControlled: true,
      enableDrag: true,
      builder: (BuildContext context) {
        return Consumer(builder: (BuildContext context, ShippingManagementVM shippingManagementVM, Widget? child) {
          return InfoBottomSheet(
              title: LocaleKeys.pleaseSpecify.tr().toText(fontSize: 28, isBold: true, letterSpacing: -1.44),
              description: Padding(
                padding: EdgeInsets.only(bottom: MediaQuery.of(context).viewInsets.bottom),
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        12.height,
                        ListView.separated(
                          shrinkWrap: true,
                          itemCount: getAvailableStatusesShippingList(shippingManagementVM.shippingRequestStatusesList, shippingRequestStatusEnum).length,
                          separatorBuilder: (BuildContext context, int index) {
                            return const Padding(
                              padding: EdgeInsets.symmetric(vertical: 3.0),
                              child: Divider(thickness: 0.5),
                            );
                          },
                          itemBuilder: (BuildContext context, int index) {
                            List<FilterListModel> list = getAvailableStatusesShippingList(shippingManagementVM.shippingRequestStatusesList, shippingRequestStatusEnum);
                            FilterListModel shippingFilterListModel = list[index];
                            int id = list[index].id;
                            return CircleCheckBoxWithTitle(
                              isChecked: shippingFilterListModel.isSelected,
                              title: shippingFilterListModel.title,
                              onSelected: () {
                                int i = shippingManagementVM.shippingRequestStatusesList.indexWhere((element) => element.id == id);
                                if (i == -1) {
                                  return;
                                }
                                shippingManagementVM.updateSelectionInShippingRequestStatuses(i);
                              },
                              selectedColor: MyColors.darkPrimaryColor,
                            );
                          },
                        ),
                        12.height,
                        TxtField(
                          maxLines: 4,
                          value: shippingManagementVM.requestStatusComments,
                          errorValue: "",
                          keyboardType: TextInputType.text,
                          hint: LocaleKeys.comment.tr(),
                          onChanged: (v) => shippingManagementVM.updateRequestStatusComments(v),
                        ),
                      ],
                    ),
                    25.height,
                    ShowFillButton(
                      title: LocaleKeys.submit.tr(),
                      onPressed: () async {
                        FilterListModel value = shippingManagementVM.shippingRequestStatusesList.firstWhere((element) => element.isSelected);
                        ShippingRequestStatusEnum shippingStatusEnum = value.id.toShippingStatusEnum();
                        bool status = await shippingManagementVM.onUpdateShippingStatusTapped(shippingStatusEnum: shippingStatusEnum, shippingRequestId: shippingRequestId, context: context);
                        if (status) {
                          pop(context);
                          int index = shippingManagementVM.shippingRequestFilterOptions.indexWhere((element) => element.isSelected);
                          int id = shippingManagementVM.shippingRequestFilterOptions[index].id;
                          await shippingManagementVM.getShippingRequestsListByFilters(shippingStatusEnum: id.toShippingStatusEnum());
                        }
                      },
                      maxWidth: double.infinity,
                    ),
                    19.height,
                  ],
                ),
              ));
        });
      },
    );
  }

  Future buildUpdateSelfPickupStatusBottomSheet({required int shippingRequestId, required SelfPickupRequestStatusEnum selfPickupRequestStatusEnum}) {
    return showModalBottomSheet(
      context: context,
      isScrollControlled: true,
      enableDrag: true,
      builder: (BuildContext context) {
        return Consumer(builder: (BuildContext context, ShippingManagementVM shippingManagementVM, Widget? child) {
          return InfoBottomSheet(
              title: LocaleKeys.pleaseSpecify.tr().toText(fontSize: 28, isBold: true, letterSpacing: -1.44),
              description: Padding(
                padding: EdgeInsets.only(bottom: MediaQuery.of(context).viewInsets.bottom),
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        12.height,
                        ListView.separated(
                          shrinkWrap: true,
                          itemCount: getAvailableStatusesPickupList(shippingManagementVM.selfPickupRequestsStatusesList, selfPickupRequestStatusEnum).length,
                          separatorBuilder: (BuildContext context, int index) {
                            return const Padding(
                              padding: EdgeInsets.symmetric(vertical: 3.0),
                              child: Divider(thickness: 0.5),
                            );
                          },
                          itemBuilder: (BuildContext context, int index) {
                            List<FilterListModel> list = getAvailableStatusesPickupList(shippingManagementVM.selfPickupRequestsStatusesList, selfPickupRequestStatusEnum);
                            FilterListModel shippingFilterListModel = list[index];
                            int id = list[index].id;
                            return CircleCheckBoxWithTitle(
                              isChecked: shippingFilterListModel.isSelected,
                              title: shippingFilterListModel.title,
                              onSelected: () {
                                int i = shippingManagementVM.selfPickupRequestsStatusesList.indexWhere((element) => element.id == id);
                                if (i == -1) {
                                  return;
                                }
                                shippingManagementVM.updateSelectionInSelfPickupRequestStatuses(i);
                              },
                              selectedColor: MyColors.darkPrimaryColor,
                            );
                          },
                        ),
                        12.height,
                        TxtField(
                          maxLines: 4,
                          value: shippingManagementVM.requestStatusComments,
                          errorValue: "",
                          keyboardType: TextInputType.text,
                          hint: LocaleKeys.comment.tr(),
                          onChanged: (v) => shippingManagementVM.updateRequestStatusComments(v),
                        ),
                      ],
                    ),
                    25.height,
                    ShowFillButton(
                      title: LocaleKeys.submit.tr(),
                      onPressed: () async {
                        FilterListModel value = shippingManagementVM.selfPickupRequestsStatusesList.firstWhere((element) => element.isSelected);
                        SelfPickupRequestStatusEnum selfPickupRequestStatusEnum = value.id.toSelfPickupStatusEnum();
                        bool status = await shippingManagementVM.onUpdateSelfPickupStatusTapped(
                          selfPickupRequestStatusEnum: selfPickupRequestStatusEnum,
                          shippingRequestId: shippingRequestId,
                          context: context,
                        );
                        if (status) {
                          pop(context);
                          int index = shippingManagementVM.selfPickupRequestsFilterOptions.indexWhere((element) => element.isSelected);
                          int id = shippingManagementVM.selfPickupRequestsFilterOptions[index].id;
                          await shippingManagementVM.getSelfPickupRequestsListByFilters(selfPickupStatusEnum: id.toSelfPickupStatusEnum());
                        }
                      },
                      maxWidth: double.infinity,
                    ),
                    19.height,
                  ],
                ),
              ));
        });
      },
    );
  }

  @override
  void dispose() {
    shippingViewModel.resetFilters();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Consumer(builder: (BuildContext context, ShippingManagementVM shippingVm, Widget? child) {
      return Scaffold(
        appBar: CustomAppBar(title: LocaleKeys.shippingManagement.tr()),
        body: Container(
          color: MyColors.backgroundColor,
          width: double.infinity,
          height: double.infinity,
          child: Column(
            children: [
              16.height,
              Row(
                children: [
                  Expanded(
                    child: ShowFillButton(
                      isFilled: !shippingVm.isSelfPickupTapped,
                      maxHeight: 55,
                      fontSize: 15,
                      title: LocaleKeys.delivery.tr(),
                      txtColor: !shippingVm.isSelfPickupTapped ? MyColors.white : MyColors.darkTextColor,
                      onPressed: () async {
                        shippingVm.updateIsSelfPickupTapped(false);
                        int index = shippingVm.shippingRequestFilterOptions.indexWhere((element) => element.isSelected);
                        int id = shippingVm.shippingRequestFilterOptions[index].id;
                        await shippingVm.getShippingRequestsListByFilters(shippingStatusEnum: id.toShippingStatusEnum());
                      },
                    ),
                  ),
                  12.width,
                  Expanded(
                    child: ShowFillButton(
                      isFilled: shippingVm.isSelfPickupTapped,
                      txtColor: shippingVm.isSelfPickupTapped ? MyColors.white : MyColors.darkTextColor,
                      maxHeight: 55,
                      fontSize: 15,
                      title: LocaleKeys.selfPickup.tr(),
                      onPressed: () async {
                        shippingVm.updateIsSelfPickupTapped(true);
                        int index = shippingVm.selfPickupRequestsFilterOptions.indexWhere((element) => element.isSelected);
                        int id = shippingVm.selfPickupRequestsFilterOptions[index].id;
                        await shippingVm.getSelfPickupRequestsListByFilters(selfPickupStatusEnum: id.toSelfPickupStatusEnum());
                      },
                    ),
                  ),
                ],
              ).horPaddingMain(),
              16.height,
              if (shippingVm.isSelfPickupTapped) ...[
                FiltersList(
                  filterList: shippingVm.selfPickupRequestsFilterOptions,
                  onFilterTapped: (index, selectedFilterId) {
                    shippingVm.applyFiltersOnSelfPickupRequests(selfPickupRequestStatusEnum: selectedFilterId.toSelfPickupStatusEnum());
                  },
                ),
              ] else ...[
                FiltersList(
                  filterList: shippingVm.shippingRequestFilterOptions,
                  onFilterTapped: (index, selectedFilterId) {
                    shippingVm.applyFiltersOnShippingRequests(shippingRequestStatusEnum: selectedFilterId.toShippingStatusEnum());
                  },
                ),
              ],
              8.height,
              Expanded(
                child: RefreshIndicator(
                  onRefresh: () async {
                    if (shippingVm.isSelfPickupTapped) {
                      int index = shippingVm.selfPickupRequestsFilterOptions.indexWhere((element) => element.isSelected);
                      int id = shippingVm.selfPickupRequestsFilterOptions[index].id;
                      await shippingVm.getSelfPickupRequestsListByFilters(selfPickupStatusEnum: id.toSelfPickupStatusEnum());
                    } else {
                      int index = shippingVm.shippingRequestFilterOptions.indexWhere((element) => element.isSelected);
                      int id = shippingVm.shippingRequestFilterOptions[index].id;
                      await shippingVm.getShippingRequestsListByFilters(shippingStatusEnum: id.toShippingStatusEnum());
                    }
                  },
                  child: (shippingVm.state == ViewState.busy)
                      ? const Center(child: CircularProgressIndicator())
                      : shippingVm.shippingRequestsList.isEmpty
                          ? Center(child: LocaleKeys.noRequeststoShow.tr().toText(fontSize: 16, color: MyColors.lightTextColor))
                          : ListView.separated(
                              itemCount: shippingVm.shippingRequestsList.length,
                              padding: const EdgeInsets.all(16),
                              itemBuilder: (context, index) {
                                ShippingRequestModel shippingRequest = shippingVm.shippingRequestsList[index];
                                return Column(
                                  crossAxisAlignment: CrossAxisAlignment.start,
                                  children: [
                                    if (shippingVm.isSelfPickupTapped) ...[
                                      Utils.statusContainerChip(
                                        text: Utils.getNameBySelfPickupRequestStatusEnum(shippingRequest.selfPickupRequestStatusEnum ?? SelfPickupRequestStatusEnum.preparingToCollect),
                                        chipColor: Utils.getChipColorBySelfPickupRequestStatusEnum(shippingRequest.selfPickupRequestStatusEnum ?? SelfPickupRequestStatusEnum.preparingToCollect),
                                      ),
                                    ] else ...[
                                      Utils.statusContainerChip(
                                        text: Utils.getNameByShippingRequestStatusEnum(shippingRequest.shippingStatusEnum ?? ShippingRequestStatusEnum.initiated),
                                        chipColor: Utils.getChipColorByShippingRequestStatusEnum(shippingRequest.shippingStatusEnum ?? ShippingRequestStatusEnum.initiated),
                                      ),
                                    ],
                                    ("${shippingRequest.request!.brand} ${shippingRequest.request!.model} | ${shippingRequest.requestID.toString()}").toText(fontSize: 16),
                                    (shippingRequest.request!.description ?? "").toText(color: MyColors.lightTextColor, fontSize: 12, fontWeight: MyFonts.Medium),
                                    if (shippingRequest.vehicleType != null && shippingRequest.vehicleType!.isNotEmpty) ...[
                                      ("${LocaleKeys.itemType.tr()}: " "${shippingRequest.vehicleType}" ?? "").toText(color: MyColors.lightTextColor, fontSize: 12, fontWeight: MyFonts.Medium),
                                    ],
                                    if (shippingRequest.comment != null && shippingRequest.comment!.isNotEmpty) ...[
                                      ("${LocaleKeys.comment.tr()}: ${shippingRequest.comment ?? ""}").toText(color: MyColors.lightTextColor, fontSize: 12, fontWeight: MyFonts.Medium),
                                    ],
                                    4.height,
                                    Row(
                                      crossAxisAlignment: CrossAxisAlignment.start,
                                      mainAxisAlignment: MainAxisAlignment.spaceBetween,
                                      children: [
                                        Row(
                                          children: [
                                            (shippingRequest.customerName ?? "").toText(color: MyColors.lightTextColor, fontSize: 12, fontWeight: MyFonts.Medium),
                                            if (shippingRequest.createdOn != null && shippingRequest.createdOn!.isNotEmpty) ...[
                                              " | ${DateTime.parse(shippingRequest.createdOn!).getTimeAgo()}".toText(color: MyColors.lightTextColor, fontSize: 12, fontWeight: MyFonts.Medium),
                                            ],
                                          ],
                                        ),
                                        if (shippingVm.isSelfPickupTapped) ...[
                                          if (shippingRequest.selfPickupRequestStatusEnum != SelfPickupRequestStatusEnum.collected) ...[
                                            const Icon(Icons.arrow_forward, color: MyColors.darkIconColor, size: 18),
                                          ],
                                        ] else ...[
                                          if (shippingRequest.shippingStatusEnum != ShippingRequestStatusEnum.delivered) ...[
                                            const Icon(Icons.arrow_forward, color: MyColors.darkIconColor, size: 18),
                                          ],
                                        ],
                                      ],
                                    ),
                                  ],
                                ).onPress(() {
                                  if (shippingVm.isSelfPickupTapped) {
                                    if (shippingRequest.selfPickupRequestStatusEnum == SelfPickupRequestStatusEnum.collected) {
                                      return;
                                    }
                                    buildUpdateSelfPickupStatusBottomSheet(shippingRequestId: shippingRequest.id!, selfPickupRequestStatusEnum: shippingRequest.selfPickupRequestStatusEnum!);
                                  } else {
                                    if (shippingRequest.shippingStatusEnum == ShippingRequestStatusEnum.delivered) {
                                      return;
                                    }
                                    buildUpdateShippingStatusBottomSheet(shippingRequestId: shippingRequest.id!, shippingRequestStatusEnum: shippingRequest.shippingStatusEnum!);
                                  }
                                }).toContainer(isShadowEnabled: true);
                              },
                              separatorBuilder: (context, index) => 16.height,
                            ),
                ),
              ),
            ],
          ),
        ),
      );
    });
  }
}
