import 'dart:developer';

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.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/chat_models/chat_message_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/requests_view_model.dart';
import 'package:mc_common_app/views/advertisement/ad_creation_steps/ad_creation_steps_containers.dart';
import 'package:mc_common_app/views/advertisement/components/picked_images_container_widget.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/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';

Future buildSendOfferBottomSheet({
  required BuildContext context,
  required RequestDetailPageArguments requestDetailPageArguments,
  required bool isFromChatScreen,
  required int? offerId,
}) {
  final requestDetail = requestDetailPageArguments.requestModel;
  final requestIndex = requestDetailPageArguments.requestIndex;
  return showModalBottomSheet(
    context: context,
    isScrollControlled: true,
    enableDrag: true,
    builder: (BuildContext context) {
      return Consumer(builder: (BuildContext context, RequestsVM requestsVM, Widget? child) {
        return InfoBottomSheet(
            title: LocaleKeys.provideOffer.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,
                      TxtField(
                        value: requestsVM.offerPrice,
                        errorValue: requestsVM.offerPriceError,
                        keyboardType: TextInputType.number,
                        hint: LocaleKeys.enterAmount.tr(),
                        numbersOnly: true,
                        onChanged: (v) => requestsVM.updateOfferPrice(v),
                      ),
                      if (requestDetail.requestType == RequestsTypeEnum.serviceRequest.getIdFromRequestTypeEnum()) ...[
                        12.height,
                        TxtField(
                          value: requestsVM.serviceItem,
                          errorValue: requestsVM.offerPriceError,
                          hint: LocaleKeys.serviceItem.tr(),
                          onChanged: (v) => requestsVM.updateServiceItem(v),
                        ),
                        12.height,
                        TxtField(
                          value: requestsVM.itemManufacturer,
                          errorValue: requestsVM.offerPriceError,
                          hint: LocaleKeys.createdBy.tr(),
                          onChanged: (v) => requestsVM.updateItemManufacturer(v),
                        ),
                        12.height,
                        TxtField(
                          errorValue: "",
                          hint: LocaleKeys.createdOn.tr(),
                          value: requestsVM.serviceItemCreatedOn,
                          isNeedClickAll: true,
                          postfixData: Icons.calendar_month_rounded,
                          postFixDataColor: MyColors.darkTextColor,
                          onTap: () async {
                            final formattedDate = await Utils.pickDateFromDatePicker(context, firstDate: DateTime(2020), lastDate: DateTime.now());
                            requestsVM.updateServiceItemCreatedOn(formattedDate);
                          },
                        ),
                      ],
                      12.height,
                      TxtField(
                        maxLines: 5,
                        value: requestsVM.offerDescription,
                        errorValue: requestsVM.offerDescriptionError,
                        keyboardType: TextInputType.text,
                        hint: LocaleKeys.description.tr(),
                        onChanged: (v) => requestsVM.updateOfferDescription(v),
                      ),
                      12.height,
                      if (requestDetail.requestType == RequestsTypeEnum.serviceRequest.getIdFromRequestTypeEnum()) ...[
                        LocaleKeys.deliveryAvailable.tr().toText(fontSize: 16),
                        8.height,
                        Container(
                          width: 50,
                          height: 30,
                          decoration: BoxDecoration(
                            color: requestsVM.isDeliveryAvailableStatus ? MyColors.darkPrimaryColor : MyColors.white,
                            borderRadius: BorderRadius.circular(25.0),
                            border: Border.all(color: MyColors.black, width: 1),
                          ),
                          child: Transform.scale(
                            scale: 0.8,
                            child: CupertinoSwitch(
                              activeColor: MyColors.darkPrimaryColor,
                              trackColor: MyColors.white,
                              thumbColor: MyColors.grey98Color,
                              value: requestsVM.isDeliveryAvailableStatus,
                              onChanged: (value) {
                                requestsVM.updateIsDeliveryAvailableStatus(value);
                              },
                            ),
                          ),
                        ),
                      ],
                      12.height,
                      if (requestsVM.pickedVehicleImages.isEmpty) ...[
                        DottedRectContainer(
                          onTap: () => context.read<RequestsVM>().pickMultipleImages(),
                          text: LocaleKeys.attachImage.tr(),
                          icon: MyAssets.attachmentIcon.buildSvg(),
                        ),
                      ],
                      if (requestsVM.pickedVehicleImages.isNotEmpty) ...[
                        16.height,
                        PickedFilesContainer(
                          pickedFiles: requestsVM.pickedVehicleImages,
                          onCrossPressedPrimary: requestsVM.removeImageFromList,
                          onAddFilePressed: () {
                            context.read<RequestsVM>().pickMultipleImages();
                          },
                        ),
                      ],
                    ],
                  ),
                  25.height,
                  ShowFillButton(
                    title: offerId == null ? LocaleKeys.submit.tr() : LocaleKeys.update.tr(),
                    maxHeight: 55,
                    onPressed: () {
                      if (offerId == null) {
                        requestsVM.onSendOfferPressed(
                          context: context,
                          offerId: offerId,
                          receiverId: requestDetail.customerID,
                          message: requestsVM.offerDescription,
                          requestId: requestDetail.id,
                          offerPrice: requestsVM.offerPrice,
                          requestModel: requestDetail,
                          isDeliveryAvailable: requestsVM.isDeliveryAvailableStatus,
                          requestIndex: requestDetailPageArguments.requestIndex,
                          isFromChatScreen: isFromChatScreen,
                          manufacturedById: 1,
                          // Todo: It should be the ID of the manufacturer
                          manufacturedOn: requestsVM.serviceItemCreatedOn,
                          serviceItemName: requestsVM.serviceItem,
                        );
                      } else {
                        requestsVM.updateOfferFromProvider(
                          message: requestsVM.offerDescription,
                          requestId: requestDetail.id,
                          offerId: offerId,
                          offerPrice: requestsVM.offerPrice,
                          isDeliveryAvailable: requestsVM.isDeliveryAvailableStatus,
                          serviceItemName: requestsVM.serviceItem,
                          manufacturedById: 1,
                          // Todo: It should be the ID of the manufacturer
                          manufacturedOn: requestsVM.serviceItemCreatedOn,
                          receiverId: requestDetail.customerId,
                          customerRequestIndex: requestIndex,
                          context: context,
                        );
                      }
                    },
                    maxWidth: double.infinity,
                  ),
                  19.height,
                ],
              ),
            ));
      });
    },
  );
}

Future buildRequestStatusUpdateSheetForProvider({required BuildContext mainContext, required int requestId}) {
  return showModalBottomSheet(
    context: mainContext,
    isScrollControlled: true,
    enableDrag: true,
    builder: (BuildContext context) {
      return Consumer(builder: (BuildContext context, RequestsVM requestVM, Widget? child) {
        return InfoBottomSheet(
            title: LocaleKeys.selectDeliveryType.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: requestVM.providerDeliveryActionsList.length,
                        separatorBuilder: (BuildContext context, int index) => const Divider(thickness: 0.5),
                        itemBuilder: (BuildContext context, int index) {
                          OfferRequestCommentModel offerRequestCommentModel = requestVM.providerDeliveryActionsList[index];
                          return CircleCheckBoxWithTitle(
                            isChecked: offerRequestCommentModel.isSelected ?? false,
                            title: '${offerRequestCommentModel.title}',
                            onSelected: () {
                              requestVM.updateSelectedProviderDeliveryAction(index);
                            },
                            selectedColor: MyColors.darkPrimaryColor,
                          );
                        },
                      ),
                    ],
                  ),
                  25.height,
                  ShowFillButton(
                    title: LocaleKeys.submit.tr(),
                    maxHeight: 55,
                    onPressed: () async {
                      // index 0-> shipping
                      // index 1-> delivery
                      pop(context);
                      bool status = false;
                      if (requestVM.selectedProviderDeliveryAction.index == 0) {
                        status = await requestVM.onActionRequestTapped(context: mainContext, requestStatusEnum: RequestStatusEnum.shipping, requestId: requestId);
                      } else if (requestVM.selectedProviderDeliveryAction.index == 1) {
                        status = await requestVM.onActionRequestTapped(context: mainContext, requestStatusEnum: RequestStatusEnum.delivery, requestId: requestId);
                      }
                      if (status) {
                        await requestVM.getRequests(isNeedToRebuild: true);
                        pop(mainContext);
                      }
                    },
                    maxWidth: double.infinity,
                  ),
                  19.height,
                ],
              ),
            ));
      });
    },
  );
}
