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/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/appointments_view_model.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/views/advertisement/components/ads_images_corousel_widget.dart';
import 'package:mc_common_app/views/chat/widgets/chat_bottom_sheets.dart';
import 'package:mc_common_app/views/requests/request_bottomsheets.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/extensions/extensions_widget.dart';
import 'package:provider/provider.dart';
import 'package:easy_localization/easy_localization.dart';

class RequestDetailPage extends StatelessWidget {
  final RequestDetailPageArguments requestDetailPageArguments;

  const RequestDetailPage({super.key, required this.requestDetailPageArguments});

  Widget buildRequestDetailActionFooter({
    required int requestId,
    required RequestStatusEnum requestStatus,
    required RequestsTypeEnum requestTypeEnum,
    required String statusText,
    required BuildContext context,
  }) {
    switch (requestStatus) {
      case RequestStatusEnum.submitted:
        return ShowFillButton(
          maxWidth: double.infinity,
          margin: const EdgeInsets.all(15),
          maxHeight: 55,
          title: LocaleKeys.specialRequestChat.tr(),
          isBold: false,
          onPressed: () => onViewChatTapped(context),
        );

      case RequestStatusEnum.inProgress:
        if (requestTypeEnum == RequestsTypeEnum.serviceRequest) {
          return Utils.buildStatusContainer(LocaleKeys.awaitingPaymentFromCustomer.tr());
        } else {
          return Utils.buildStatusContainer(LocaleKeys.awaitingResponseFromCustomer.tr());
        }

      case RequestStatusEnum.paid:
        if (AppState().currentAppType == AppType.provider) {
          return ShowFillButton(
            maxWidth: double.infinity,
            margin: const EdgeInsets.all(15),
            maxHeight: 55,
            title: LocaleKeys.selectDeliveryType.tr(),
            isBold: false,
            onPressed: () {
              buildRequestStatusUpdateSheetForProvider(mainContext: context, requestId: requestId);
            },
          );
        } else {
          return Utils.buildStatusContainer(LocaleKeys.awaitingResponseFromProvider.tr());
        }

      case RequestStatusEnum.shipping:
      case RequestStatusEnum.delivery:
        if (AppState().currentAppType == AppType.provider) {
          return Utils.buildStatusContainer(LocaleKeys.shippingManagementInstruction.tr());
        } else {
          return ShowFillButton(
            maxWidth: double.infinity,
            margin: const EdgeInsets.all(15),
            maxHeight: 55,
            title: LocaleKeys.completeDeal.tr(),
            onPressed: () {
              return dealCompletedConsentBottomSheet(
                mainContext: context,
                requestStatusEnum: RequestStatusEnum.completed,
                requestId: requestId,
                acceptRequestOffer: () {},
              );
            },
          );
        }
      case RequestStatusEnum.completed:
      case RequestStatusEnum.cancelled:
      case RequestStatusEnum.expired:
      case RequestStatusEnum.pending:
        return Utils.buildStatusContainer(statusText);
    }
  }

  Future<void> onViewChatTapped(BuildContext context) async {
    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,
    );
    final chatVM = context.read<ChatVM>();
    await chatVM
        .getRequestsChatMessagesForProvider(
          customerId: requestDetailPageArguments.requestModel.customerId,
          context: context,
          requestOfferId: 0,
          requestId: requestDetailPageArguments.requestModel.id,
          customerRequestIndex: requestDetailPageArguments.requestIndex,
        )
        .whenComplete(() => navigateWithName(context, AppRoutes.chatView, arguments: chatViewArguments));
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: CustomAppBar(
        title: LocaleKeys.requestDetail.tr(),
        actions: [
          (context.read<RequestsVM>().isOfferSent || requestDetailPageArguments.requestModel.isChatted)
              ? Padding(
                  padding: const EdgeInsets.only(top: 8, bottom: 8, right: 21),
                  child: const Icon(Icons.messenger_outline_rounded, color: Colors.black, size: 18).toContainer(
                    borderRadius: 100,
                    borderColor: MyColors.lightGreyEFColor,
                    isEnabledBorder: true,
                  ),
                ).onPress(() => onViewChatTapped(context))
              : const SizedBox(),
        ],
      ),
      body: SizedBox(
        width: double.infinity,
        height: double.infinity,
        child: Column(
          mainAxisAlignment: MainAxisAlignment.spaceBetween,
          children: [
            Column(
              children: [
                ImagesCorouselWidget(imagesList: requestDetailPageArguments.requestModel.requestImages ?? []),
                24.height,
                buildRequestDetailsContainer(context),
              ],
            ).toWhiteContainer(
              width: double.infinity,
              allPading: 12,
              margin: const EdgeInsets.only(top: 21, right: 21, left: 21),
            ),
            if (!context.read<RequestsVM>().isOfferSent && !requestDetailPageArguments.requestModel.isChatted) ...[
              ShowFillButton(
                maxWidth: double.infinity,
                margin: const EdgeInsets.all(15),
                maxHeight: 55,
                title: LocaleKeys.provideOffer.tr(),
                isBold: false,
                fontSize: 18,
                onPressed: () => buildSendOfferBottomSheet(
                  context: context,
                  requestDetailPageArguments: requestDetailPageArguments,
                  isFromChatScreen: false,
                  offerId: null, // null means creating new offer
                ),
              ),
            ] else ...[
              buildRequestDetailActionFooter(
                requestId: requestDetailPageArguments.requestModel.id,
                requestStatus: requestDetailPageArguments.requestModel.requestStatus,
                statusText: "Offer ${requestDetailPageArguments.requestModel.requestStatusName}",
                context: context,
                requestTypeEnum: requestDetailPageArguments.requestModel.requestType.toRequestTypeEnum(),
              ),
            ],
          ],
        ),
      ),
    );
  }

  Widget buildRequestDetailsContainer(BuildContext context) {
    final requestDetail = requestDetailPageArguments.requestModel;
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Row(
          mainAxisAlignment: MainAxisAlignment.start,
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Expanded(
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                mainAxisAlignment: MainAxisAlignment.start,
                children: [
                  requestDetail.vehicleTypeName.toText(fontSize: 16, letterSpacing: -0.64),
                  showItem("${LocaleKeys.brand.tr()}: ", requestDetail.brand),
                  showItem("${LocaleKeys.model.tr()}: ", requestDetail.model),
                  showItem("${LocaleKeys.year.tr()}: ", "${requestDetail.year}"),
                ],
              ),
            ),
            Column(
              crossAxisAlignment: CrossAxisAlignment.end,
              mainAxisAlignment: MainAxisAlignment.start,
              children: [
                "${requestDetail.city ?? ""} ${requestDetail.countryName}".toText(
                  color: MyColors.lightTextColor,
                ),
                if (requestDetail.createdOn != null) ...[
                  DateTime.parse(requestDetail.createdOn!).getTimeAgo().toText(
                        color: MyColors.lightTextColor,
                      ),
                ],
              ],
            ),
          ],
        ),
        if (requestDetail.customerName.isNotEmpty) ...[
          showItem("${LocaleKeys.customerName.tr()}: ", requestDetail.customerName),
        ],
        showItem("${LocaleKeys.description.tr()}: ", requestDetail.description),
        16.height,

        if (AppState().currentAppType == AppType.provider &&
            (requestDetailPageArguments.requestModel.requestStatus == RequestStatusEnum.inProgress || requestDetailPageArguments.requestModel.requestStatus == RequestStatusEnum.submitted)) ...[
          Row(
            mainAxisAlignment: MainAxisAlignment.end,
            children: [
              ("${LocaleKeys.reportComplaint.tr()}?").toText(fontSize: 14, color: MyColors.darkTextColor),
            ],
          ).onPress(
            () {
              int customerID = requestDetailPageArguments.requestModel.customerId;
              int complainType = 2;
              String customerName = requestDetailPageArguments.requestModel.customerName;

              context.read<AppointmentsVM>().buildComplaintBottomSheet(
                    customerID: customerID,
                    customerName: customerName,
                    complainType: complainType,
                    context: context,
                  );
            },
          ),
        ],

        // showItem("${LocaleKeys.priceRange.tr()}:", ""),
        // Row(
        //   children: [
        //     Expanded(
        //       child: Row(
        //         mainAxisAlignment: MainAxisAlignment.spaceBetween,
        //         crossAxisAlignment: CrossAxisAlignment.end,
        //         children: [
        //           Row(
        //             crossAxisAlignment: CrossAxisAlignment.end,
        //             children: [
        //               "${requestDetail.price.toInt()}".toText(fontSize: 19, isBold: true, letterSpacing: -1.16),
        //               2.width,
        //               LocaleKeys.sar.tr().toText(color: MyColors.lightTextColor, fontSize: 10, letterSpacing: -0.4),
        //             ],
        //           ),
        //           Row(
        //             children: [
        //               Utils.statusContainerChip(
        //                 text: (requestDetail.requestStatusName),
        //                 chipColor: MyColors.grey98Color.withOpacity(0.1),
        //                 textColor: MyColors.lightTextColor,
        //               ),
        //             ],
        //           ),
        //         ],
        //       ),
        //     ),
        //     // const Icon(Icons.arrow_forward)
        //   ],
        // ),
      ],
    );
  }

  Widget showItem(String title, String value) {
    return Row(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        if (title.isNotEmpty) title.toText(color: MyColors.lightTextColor, letterSpacing: -0.48),
        if (title.isNotEmpty) 2.width,
        if (value.isNotEmpty) Expanded(child: value.toText(letterSpacing: -0.48)),
      ],
    );
  }
}
