import 'dart:async';
import 'dart:developer';
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/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/categories_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();
      }
      await shippingViewModel.getShippingRequestsListByFilters();
    });
    super.initState();
  }

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

    for (var element in list) {
      if (element.id > shippingRequestStatusEnum.getIdFromShippingStatusEnum()) {
        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: getAvailableStatusesList(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 = getAvailableStatusesList(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);
                          await shippingManagementVM.getShippingRequestsListByFilters(shippingStatusEnum: index.toShippingStatusEnum());
                        }
                      },
                      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,
                FiltersList(
                  filterList: shippingVm.shippingRequestFilterOptions,
                  onFilterTapped: (index, selectedFilterId) {
                    shippingVm.applyFiltersOnShippingRequests(shippingRequestStatusEnum: selectedFilterId.toShippingStatusEnum());
                  },
                ),
                8.height,
                Expanded(
                    child: RefreshIndicator(
                  onRefresh: () async {
                    int index = shippingVm.shippingRequestFilterOptions.indexWhere((element) => element.isSelected);
                    await shippingVm.getShippingRequestsListByFilters(shippingStatusEnum: index.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: [
                                    Utils.statusContainerChip(
                                      text: Utils.getNameByShippingRequestStatusEnum(shippingRequest.shippingStatusEnum ?? ShippingRequestStatusEnum.initiated),
                                      chipColor: Utils.getChipColorByShippingRequestStatusEnum(shippingRequest.shippingStatusEnum ?? ShippingRequestStatusEnum.initiated),
                                    ),
                                    ("${shippingRequest.request!.brand} ${shippingRequest.request!.model} | ${shippingRequest.id.toString()}").toText(fontSize: 16),
                                    (shippingRequest.request!.description ?? "").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 (shippingRequest.shippingStatusEnum != ShippingRequestStatusEnum.delivered) ...[
                                          const Icon(Icons.arrow_forward, color: MyColors.darkIconColor, size: 18),
                                        ],
                                      ],
                                    ),
                                  ],
                                ).onPress(() {
                                  if (shippingRequest.shippingStatusEnum == ShippingRequestStatusEnum.delivered) {
                                    return;
                                  }
                                  buildUpdateShippingStatusBottomSheet(shippingRequestId: shippingRequest.id!, shippingRequestStatusEnum: shippingRequest.shippingStatusEnum!);
                                }).toContainer(isShadowEnabled: true);
                              },
                              separatorBuilder: (context, index) => 16.height,
                            ),
                )),
              ],
            ),
          ));
    });
  }
}
