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/provider_offers_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 OfferListPage extends StatefulWidget {
  final int requestId;

  const OfferListPage({super.key, required this.requestId});

  @override
  State<OfferListPage> createState() => _OfferListPageState();
}

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

  _onRefresh() async {
    scheduleMicrotask(() async {
      ChatVM chatVM = context.read<ChatVM>();
      await chatVM.getOffersFromProvidersByRequest(requestId: widget.requestId);
    });
  }

  @override
  Widget build(BuildContext context) {
    return Consumer<ChatVM>(builder: (context, ChatVM chatVM, Widget? child) {
      return Scaffold(
        appBar: CustomAppBar(title: LocaleKeys.offers.tr()),
        body: RefreshIndicator(
          onRefresh: () async {
            _onRefresh();
          },
          child: chatVM.state == ViewState.busy
              ? const Center(child: CircularProgressIndicator())
              : chatVM.serviceProviderOffersList.isEmpty
                  ? Center(
                      child: LocaleKeys.noOffersShow.tr().toText(
                            fontSize: 16,
                            color: MyColors.lightTextColor,
                          ),
                    )
                  : ListView.separated(
                      itemCount: chatVM.serviceProviderOffersList.length,
                      padding: const EdgeInsets.all(16),
                      itemBuilder: (context, index) {
                        ServiceProvidersOffers offersModel = chatVM.serviceProviderOffersList[index];
                        return Column(
                          crossAxisAlignment: CrossAxisAlignment.start,
                          children: [
                            Utils.statusContainerChip(
                              text: Utils.getNameByRequestOfferStatusEnum(offersModel.requestOfferStatusEnum!),
                              chipColor: Utils.getChipColorByRequestOfferStatusEnum(offersModel.requestOfferStatusEnum!),
                            ),
                            Row(
                              mainAxisAlignment: MainAxisAlignment.spaceBetween,
                              crossAxisAlignment: CrossAxisAlignment.start,
                              children: [
                                (offersModel.name ?? "").toText(
                                  fontSize: 16,
                                  isBold: true,
                                ),
                                if (offersModel.offerCount != null && offersModel.offerCount! > 0) ...[
                                  Center(
                                    child: "${offersModel.offerCount}".toText(
                                      color: Colors.white,
                                      isBold: true,
                                      fontSize: 10,
                                    ),
                                  ).toContainer(
                                    backgroundColor: MyColors.cancelledColor,
                                    borderRadius: 100,
                                    paddingAll: 1,
                                    width: 22,
                                    height: 22,
                                  ),
                                ],
                              ],
                            ),
                            8.height,
                            Row(
                              crossAxisAlignment: CrossAxisAlignment.start,
                              mainAxisAlignment: MainAxisAlignment.spaceBetween,
                              children: [
                                Row(
                                  children: [
                                    "${offersModel.companyName}".toText(color: MyColors.lightTextColor, fontSize: 14),
                                    if (offersModel.createdOn != null && offersModel.createdOn!.isNotEmpty) ...[
                                      " | ${DateTime.parse(offersModel.createdOn!).getTimeAgo()}".toText(color: MyColors.lightTextColor, fontSize: 14),
                                    ],
                                  ],
                                ),
                                const Icon(Icons.arrow_forward, color: MyColors.darkIconColor, size: 18),
                              ],
                            ),
                          ],
                        ).onPress(() async {
                          context.read<RequestsVM>().currentSelectedOffer = offersModel;

                          ChatViewArgumentsForRequest chatViewArgumentsForRequest = ChatViewArgumentsForRequest(
                            chatTypeEnum: ChatTypeEnum.requestOffer,
                            receiverId: "${offersModel.providerUserId}",
                            senderId: AppState().getUser.data!.userInfo!.userId.toString(),
                            requestId: widget.requestId,
                            providerIndex: index,
                            requestModel: context.read<RequestsVM>().currentSelectedRequest,
                            requestIndex: -1,
                          );

                          ChatViewArguments chatViewArguments = ChatViewArguments(chatTypeEnum: ChatTypeEnum.requestOffer, chatViewArgumentsForRequest: chatViewArgumentsForRequest);

                          final chatVM = context.read<ChatVM>();

                          await chatVM
                              .getRequestsChatMessagesForCustomer(
                            context: context,
                            providerId: offersModel.providerId ?? 0,
                            requestOfferId: 0,
                            requestId: widget.requestId,
                            providerOfferIndex: index,
                          )
                              .whenComplete(() {
                            chatVM.serviceProviderOffersList[index].offerCount = 0;
                            navigateWithName(context, AppRoutes.chatView, arguments: chatViewArguments);
                          });
                        }).toContainer(isShadowEnabled: true);
                      },
                      separatorBuilder: (context, index) => 16.height,
                    ),
        ),
      );
    });
  }
}
