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/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/requests_models/offers_model.dart';
import 'package:mc_common_app/models/requests_models/offers_unread_chat_model.dart';
import 'package:mc_common_app/models/requests_models/provider_offers_model.dart';
import 'package:mc_common_app/models/requests_models/providers_offers_chat_model.dart';
import 'package:mc_common_app/models/requests_models/request_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/chat_view_model.dart';
import 'package:mc_common_app/view_models/requests_view_model.dart';
import 'package:mc_common_app/widgets/common_widgets/app_bar.dart';
import 'package:mc_common_app/widgets/extensions/extensions_widget.dart';
import 'package:provider/provider.dart';
import 'package:easy_localization/easy_localization.dart';

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

  @override
  State<ProvidersChatListPage> createState() => _ProvidersChatListPageState();
}

class _ProvidersChatListPageState extends State<ProvidersChatListPage> {
  @override
  void initState() {
    _onRefresh();
    super.initState();
  }

  _onRefresh() async {
    scheduleMicrotask(() async {
      RequestsVM requestsVM = context.read<RequestsVM>();
      await requestsVM.getOffersChatsUnreadList(userId: AppState().getUser.data!.userInfo!.userId ?? "", context: context);
    });
  }

  Future<void> onChatTapped({required BuildContext context, required int requestID}) async {
    final requestsVM = context.read<RequestsVM>();
    final chatVM = context.read<ChatVM>();

    int requestIndex = requestsVM.myFilteredRequests.indexWhere((request) => request.id == requestID);
    log("requestIndex1: $requestIndex");

    if (requestIndex == -1) {
      RequestsTypeEnum requestTypeEnum = requestsVM.requestsTypeFilterOptions.firstWhere((element) => element.isSelected).id.toRequestTypeEnum();
      if (requestTypeEnum == RequestsTypeEnum.specialCarRequest) {
        requestTypeEnum = RequestsTypeEnum.serviceRequest;
      } else {
        requestTypeEnum = RequestsTypeEnum.specialCarRequest;
      }
      await requestsVM.applyFilterOnRequestsVM(requestsTypeEnum: requestTypeEnum);

      requestIndex = requestsVM.myFilteredRequests.indexWhere((request) => request.id == requestID);
    }

    log("requestIndex2: $requestIndex");

    if (requestIndex != -1) {
      RequestModel request = requestsVM.myFilteredRequests[requestIndex];
      requestsVM.updateCurrentSelectedRequest(request);
      // if (request.requestStatus == RequestStatusEnum.pending || request.requestStatus == RequestStatusEnum.cancelled || request.requestStatus == RequestStatusEnum.expired) {
      //   Utils.showToast("${LocaleKeys.requests.tr()} ${request.requestStatusName}");
      //   return;
      // }
      RequestDetailPageArguments requestDetailPageArguments = RequestDetailPageArguments(requestIndex: requestIndex, requestModel: request);
      ChatViewArgumentsForRequest chatViewArgumentsForRequest = ChatViewArgumentsForRequest(
        chatTypeEnum: ChatTypeEnum.requestOffer,
        receiverId: requestDetailPageArguments.requestModel.customerID,
        senderId: AppState().getUser.data!.userInfo!.userId.toString(),
        requestId: requestDetailPageArguments.requestModel.id,
        providerIndex: -1,
        // This will be only sent in case of customer
        requestModel: requestDetailPageArguments.requestModel,
        requestIndex: requestDetailPageArguments.requestIndex, // This will be only sent in case of provider
      );
      ChatViewArguments chatViewArguments = ChatViewArguments(
        chatTypeEnum: ChatTypeEnum.requestOffer,
        chatViewArgumentsForRequest: chatViewArgumentsForRequest,
      );

      await chatVM
          .getRequestsChatMessagesForProvider(
            customerId: requestDetailPageArguments.requestModel.customerId,
            context: navigatorKey.currentState!.overlay!.context,
            requestOfferId: 0,
            requestId: requestDetailPageArguments.requestModel.id,
            customerRequestIndex: requestDetailPageArguments.requestIndex,
          )
          .whenComplete(() => navigateWithName(navigatorKey.currentState!.overlay!.context, AppRoutes.chatView, arguments: chatViewArguments));
    }
  }

  @override
  Widget build(BuildContext context) {
    return Consumer<RequestsVM>(builder: (context, RequestsVM requestsVM, Widget? child) {
      return Scaffold(
        appBar: CustomAppBar(title: LocaleKeys.specialRequestChat.tr()),
        body: RefreshIndicator(
          onRefresh: () async {
            _onRefresh();
          },
          child: requestsVM.state == ViewState.busy
              ? const Center(child: CircularProgressIndicator())
              : requestsVM.offersUnreadChatModel == null || requestsVM.offersUnreadChatModel!.reqChatUnread.isEmpty
                  ? Center(
                      child: LocaleKeys.noOffersShow.tr().toText(
                            fontSize: 16,
                            color: MyColors.lightTextColor,
                          ),
                    )
                  : ListView.separated(
                      itemCount: requestsVM.offersUnreadChatModel!.reqChatUnread.length,
                      padding: const EdgeInsets.all(16),
                      itemBuilder: (context, index) {
                        OffersUnreadChatDataModel offersUnreadChatDataModel = requestsVM.offersUnreadChatModel!.reqChatUnread[index];
                        return Column(
                          crossAxisAlignment: CrossAxisAlignment.start,
                          children: [
                            // Utils.statusContainerChip(
                            //   text: Utils.getNameByRequestOfferStatusEnum(providerOffersChatsModel.requestOfferStatusEnum!),
                            //   chipColor: Utils.getChipColorByRequestOfferStatusEnum(providerOffersChatsModel.requestOfferStatusEnum!),
                            // ),
                            Row(
                              mainAxisAlignment: MainAxisAlignment.spaceBetween,
                              crossAxisAlignment: CrossAxisAlignment.start,
                              children: [
                                (offersUnreadChatDataModel.customerName).toText(
                                  fontSize: 16,
                                  isBold: true,
                                ),
                                if (offersUnreadChatDataModel.unreadMessagesCount > 0) ...[
                                  Center(
                                    child: "${offersUnreadChatDataModel.unreadMessagesCount}".toText(
                                      color: Colors.white,
                                      isBold: true,
                                      fontSize: 10,
                                    ),
                                  ).toContainer(
                                    backgroundColor: MyColors.cancelledColor,
                                    borderRadius: 100,
                                    paddingAll: 1,
                                    width: 22,
                                    height: 22,
                                  ),
                                ],
                              ],
                            ),

                            4.height,
                            Row(
                              crossAxisAlignment: CrossAxisAlignment.start,
                              mainAxisAlignment: MainAxisAlignment.spaceBetween,
                              children: [
                                Expanded(
                                  child: offersUnreadChatDataModel.lastChatText.toText(color: MyColors.lightTextColor, fontSize: 14),
                                ),
                                4.height,
                                if (offersUnreadChatDataModel.lastChatTime.isNotEmpty) ...[
                                  DateTime.parse(offersUnreadChatDataModel.lastChatTime).getTimeAgo().toText(color: MyColors.lightTextColor, fontSize: 12),
                                ],
                              ],
                            ),
                            4.height,
                            const Row(
                              mainAxisAlignment: MainAxisAlignment.end,
                              children: [
                                Icon(Icons.arrow_forward, color: MyColors.darkIconColor, size: 18),
                              ],
                            ),
                          ],
                        ).onPress(() async {
                          requestsVM.offersUnreadChatModel!.reqChatUnread[index].unreadMessagesCount = 0;
                          await onChatTapped(context: context, requestID: offersUnreadChatDataModel.requestID ?? 0);
                        }).toContainer(isShadowEnabled: true);
                      },
                      separatorBuilder: (context, index) => 16.height,
                    ),
        ),
      );
    });
  }
}
