import 'dart:async';
import 'dart:developer';

import 'package:easy_localization/easy_localization.dart';
import 'package:flutter/material.dart';
import 'package:mc_common_app/classes/app_state.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/user_models/user.dart';
import 'package:mc_common_app/theme/colors.dart';
import 'package:mc_common_app/utils/date_helper.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_review_containers.dart';
import 'package:mc_common_app/views/location_views/pick_location_page.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/common_widgets/filters_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';

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

  @override
  State<ReviewRequestOffer> createState() => _ReviewRequestOfferState();
}

class _ReviewRequestOfferState extends State<ReviewRequestOffer> {
  @override
  void initState() {
    final requestVM = context.read<RequestsVM>();
    log("requestVM.acceptedRequestOffer!.requestDeliveryOption: ${requestVM.acceptedRequestOffer!.requestDeliveryOption}");
    // if (requestVM.acceptedRequestOffer != null && requestVM.acceptedRequestOffer!.requestDeliveryOption == RequestDeliveryOptionEnum.both) {
    populateRequestDeliveryOptions();
    // }

    if (requestVM.currentSelectedRequest != null && requestVM.currentSelectedRequest!.address.isEmpty) {
      requestVM.addressSparePartRequestDelivery = "";
      WidgetsBinding.instance.addPostFrameCallback((_) async => buildLocationInformationEditBottomSheet(context, requestVM));
    }
    super.initState();
  }

  @override
  void dispose() {
    super.dispose();
  }

  populateRequestDeliveryOptions() {
    scheduleMicrotask(() {
      final requestVM = context.read<RequestsVM>();

      requestVM.populateRequestDeliveryOptions();
      requestVM.updateAdditionalAddressSparePartRequestDelivery(requestVM.currentSelectedRequest!.additionalAddressDetails, false);
    });
  }

  Widget buildPersonalInformation() {
    UserInfo userInfo = AppState().getUser.data!.userInfo!;
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Row(
          mainAxisAlignment: MainAxisAlignment.spaceBetween,
          children: [
            LocaleKeys.personalInformation.tr().toText(fontSize: 18),
            const SizedBox(),
          ],
        ),
        8.height,
        Row(
          mainAxisAlignment: MainAxisAlignment.start,
          children: [
            Expanded(
              flex: 5,
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  SingleDetailWidget(text: "${userInfo.firstName ?? ""} ${userInfo.lastName ?? ""}", type: LocaleKeys.name.tr()),
                  16.height,
                  SingleDetailWidget(text: userInfo.email ?? "", type: LocaleKeys.email.tr()),
                ],
              ),
            ),
            Expanded(
              flex: 5,
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  SingleDetailWidget(text: userInfo.mobileNo ?? "", type: LocaleKeys.phone.tr()),
                  16.height,
                  const SingleDetailWidget(text: "", type: ""),
                ],
              ),
            ),
          ],
        ),
      ],
    );
  }

  Widget buildLocationInformation(BuildContext context) {
    final requestVM = context.watch<RequestsVM>();
    String address = "";

    if (requestVM.acceptedRequestOffer != null && requestVM.acceptedRequestOffer!.requestDeliveryOption == RequestDeliveryOptionEnum.delivery) {
      address = requestVM.currentSelectedRequest!.address;
    } else if (requestVM.acceptedRequestOffer != null && requestVM.acceptedRequestOffer!.requestDeliveryOption == RequestDeliveryOptionEnum.selfPickup) {
      address = requestVM.currentSelectedOffer!.providerAddress ?? "";
    } else {
      if (requestVM.selectedDeliveryOptionEnum == RequestDeliveryOptionEnum.delivery) {
        address = requestVM.currentSelectedRequest!.address;
      } else if (requestVM.selectedDeliveryOptionEnum == RequestDeliveryOptionEnum.selfPickup) {
        address = requestVM.currentSelectedOffer!.providerAddress ?? "";
      } else {
        address = "";
      }
    }
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        LocaleKeys.locationInformation.tr().toText(fontSize: 18),

        // Row(
        //   mainAxisAlignment: MainAxisAlignment.spaceBetween,
        //   children: [
        //     LocaleKeys.locationInformation.tr().toText(fontSize: 18),
        //     MyAssets.icEdit.buildSvg().onPress(() => buildLocationInformationEditBottomSheet(context, requestVM)),
        //   ],
        // ),
        8.height,
        FiltersList(
          filterList: requestVM.deliveryOptionsForReviewRequest,
          onFilterTapped: (index, selectedFilterId) async {
            int response = await requestVM.onRequestDeliveryOptionTapped(
                context: context,
                requestID: requestVM.currentSelectedRequest!.id,
                reqOfferId: requestVM.acceptedRequestOffer!.id ?? 0,
                deliveryOptionEnum: selectedFilterId.toRequestDeliveryOptionEnum());

            if (response != -1) {
              requestVM.updateSelectedDeliveryOptionEnum(selectedFilterId.toRequestDeliveryOptionEnum());
            }
          },
          needLeftPadding: false,
        ).paddingOnly(bottom: 8),
        if (requestVM.selectedDeliveryOptionEnumError.isNotEmpty) ...[
          requestVM.selectedDeliveryOptionEnumError.toText(fontSize: 12, color: Colors.red),
        ],
        if (requestVM.selectedDeliveryOptionEnum != null) ...[
          Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              SingleDetailWidget(text: address, type: LocaleKeys.location.tr()),
              if (requestVM.selectedDeliveryOptionEnum == RequestDeliveryOptionEnum.delivery) ...[
                8.height,
                Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Row(
                      mainAxisAlignment: MainAxisAlignment.spaceBetween,
                      children: [
                        ("${LocaleKeys.additionalAddressDetails.tr()}:").toText(fontSize: 12, color: MyColors.lightTextColor),
                        MyAssets.icEdit.buildSvg(height: 15).onPress(() => buildLocationInformationEditBottomSheet(context, requestVM)),
                      ],
                    ),
                    (requestVM.additionalAddressSparePartRequestDelivery).toText(fontSize: 14, color: MyColors.darkTextColor),
                  ],
                ),
              ] else if (requestVM.selectedDeliveryOptionEnum == RequestDeliveryOptionEnum.selfPickup) ...[
                Row(
                  children: [
                    LocaleKeys.openMapLocation.tr().toText(
                          fontSize: 12,
                          isBold: true,
                          color: MyColors.primaryColor,
                          isUnderLine: true,
                        ),
                    4.width,
                    Image.asset(
                      MyAssets.icRightUpPng,
                      height: 6,
                      width: 6,
                      color: MyColors.primaryColor,
                    ),
                  ],
                ).onPress(() async {
                  double latitude, longitude = 0.0;
                  latitude = double.parse(requestVM.currentSelectedOffer!.providerLatitude ?? "0.0");
                  longitude = double.parse(requestVM.currentSelectedOffer!.providerLongitude ?? "0.0");
                  await Utils.openLocationInMaps(latitude: latitude, longitude: longitude);
                })
              ],
            ],
          ),
        ],
      ],
    );
  }

  Widget buildServiceInformation(BuildContext context) {
    final requestVM = context.read<RequestsVM>();

    String manufacturedOnFormattedDate = "";
    if (requestVM.acceptedRequestOffer!.manufacturedOn != null) {
      manufacturedOnFormattedDate = DateHelper.formatAsDayMonthYear(DateHelper.parseStringToDate(DateHelper.formatDateT(requestVM.acceptedRequestOffer!.manufacturedOn.toString() ?? "")));
    }
    String requestCreatedOn = "";
    if (requestVM.currentSelectedRequest!.createdOn != null) {
      requestCreatedOn = DateHelper.formatAsDayMonthYear(DateHelper.parseStringToDate(DateHelper.formatDateT(requestVM.currentSelectedRequest!.createdOn.toString() ?? "")));
    }
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Row(
          mainAxisAlignment: MainAxisAlignment.spaceBetween,
          children: <Widget>[
            LocaleKeys.serviceInformation.tr().toText(fontSize: 18),
            const SizedBox(),
          ],
        ),
        8.height,
        Row(
          mainAxisAlignment: MainAxisAlignment.start,
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Expanded(
              flex: 6,
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  SingleDetailWidget(text: requestVM.currentSelectedRequest!.vehicleTypeName, type: LocaleKeys.vehicleType.tr()),
                  16.height,
                  SingleDetailWidget(text: '${requestVM.currentSelectedRequest!.model} ${requestVM.currentSelectedRequest!.year}', type: LocaleKeys.model.tr()),
                  if (requestVM.acceptedRequestOffer!.manufacturedByName != null) ...[
                    16.height,
                    SingleDetailWidget(text: (requestVM.acceptedRequestOffer!.manufacturedByName ?? "").toString(), type: LocaleKeys.manufacturedBy.tr()),
                  ],
                  // 16.height,
                  // SingleDetailWidget(text: "${requestVM.acceptedRequestOffer!.price.toString()} ${LocaleKeys.sar.tr()}", type: LocaleKeys.offerPrice.tr()),
                  16.height,
                  SingleDetailWidget(text: requestVM.acceptedRequestOfferProviderName ?? "", type: LocaleKeys.providerName.tr()),

                  16.height,
                  SingleDetailWidget(text: LocaleKeys.online.tr(), type: LocaleKeys.paymentType.tr()),
                ],
              ),
            ),
            Expanded(
              flex: 5,
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                mainAxisAlignment: MainAxisAlignment.start,
                children: [
                  SingleDetailWidget(text: requestVM.currentSelectedRequest!.brand, type: LocaleKeys.vehicleBrand.tr()),
                  16.height,
                  SingleDetailWidget(text: requestVM.acceptedRequestOffer!.serviceItemName ?? "", type: LocaleKeys.serviceName.tr()),
                  if (manufacturedOnFormattedDate.isNotEmpty) ...[
                    16.height,
                    SingleDetailWidget(text: manufacturedOnFormattedDate, type: LocaleKeys.manufacturedOn.tr()),
                  ],
                  16.height,
                  SingleDetailWidget(text: "${requestVM.acceptedRequestOffer!.price.toString()} ${LocaleKeys.sar.tr()}", type: LocaleKeys.offerPrice.tr()),
                  if (requestCreatedOn.isNotEmpty) ...[
                    16.height,
                    SingleDetailWidget(text: requestCreatedOn, type: LocaleKeys.requestCreatedOn.tr()),
                  ],
                ],
              ),
            ),
          ],
        ),
        16.height,
        SingleDetailWidget(text: requestVM.currentSelectedRequest!.description, type: LocaleKeys.description.tr()),
      ],
    );
  }

  Future buildLocationInformationEditBottomSheet(BuildContext context, RequestsVM requestsVM) async {
    String additionalDetails = "";
    return showModalBottomSheet(
      context: context,
      isScrollControlled: true,
      enableDrag: true,
      builder: (BuildContext context) {
        return InfoBottomSheet(
          title: LocaleKeys.locationInformation.tr().toText(fontSize: 28, isBold: true, letterSpacing: -1.44),
          description: Padding(
            padding: MediaQuery.of(context).viewInsets,
            child: StatefulBuilder(
              builder: (BuildContext context, setState) {
                return Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    LocaleKeys.updateYourLocationInfo.tr().toText(fontSize: 14, fontWeight: MyFonts.Medium),
                    // 8.height,
                    // TxtField(
                    //   hint: LocaleKeys.address.tr(),
                    //   isNeedClickAll: false,
                    //   value: requestsVM.addressSparePartRequestDelivery,
                    //   postfixWidget: IconButton(
                    //       icon: const Icon(
                    //         size: 28,
                    //         Icons.add_location_outlined,
                    //       ),
                    //       onPressed: () {
                    //         navigateTo(
                    //           context,
                    //           PickLocationPage(
                    //             onPickAddress: (double latitude, double longitude, String address) {
                    //               requestsVM.updateAddressSparePartRequestDelivery(address);
                    //               setState(() {});
                    //             },
                    //           ),
                    //         );
                    //       }),
                    //   onChanged: (e) => requestsVM.updateAddressSparePartRequestDelivery(e),
                    // ),
                    8.height,
                    TxtField(
                        maxLines: 2,
                        hint: LocaleKeys.additionalAddressDetails.tr(),
                        isNeedClickAll: false,
                        value: requestsVM.additionalAddressSparePartRequestDelivery,
                        onChanged: (e) {
                          additionalDetails = e;
                        }),
                    19.height,
                    Row(
                      children: [
                        Expanded(
                          child: ShowFillButton(
                            title: LocaleKeys.submit.tr(),
                            onPressed: () async {
                              bool status = await requestsVM.updateRequestAdditionalAddress(context: context, additionalAddress: additionalDetails, requestId: requestsVM.currentSelectedRequest!.id);

                              if (status) {
                                requestsVM.updateAdditionalAddressSparePartRequestDelivery(additionalDetails, true);
                                requestsVM.notifyListeners();
                                pop(context);
                              }
                            },
                          ),
                        )
                      ],
                    ),
                    25.height,
                  ],
                );
              },
            ),
          ),
        );
      },
    );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: CustomAppBar(
        title: LocaleKeys.offerSummary.tr(),
        isRemoveBackButton: false,
        isDrawerEnabled: false,
        onBackButtonTapped: () => Navigator.pop(context),
        actions: [
          IconButton(
            onPressed: () {
              final requestVM = context.read<RequestsVM>();

              Utils.buildProviderContactInfoBottomSheet(
                context: context,
                email: requestVM.currentSelectedOffer!.email,
                mobileNo: requestVM.currentSelectedOffer!.mobileNo,
              );
            },
            icon: const Icon(Icons.help_outline_outlined).paddingOnly(right: 21),
          ),
        ],
      ),
      body: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          SingleChildScrollView(
            child: Column(
              children: [
                10.height,
                buildPersonalInformation().toWhiteContainer(width: double.infinity, allPading: 12, margin: const EdgeInsets.symmetric(horizontal: 21, vertical: 4)),
                10.height,
                buildLocationInformation(context).toWhiteContainer(width: double.infinity, allPading: 12, margin: const EdgeInsets.symmetric(horizontal: 21, vertical: 4)),
                10.height,
                buildServiceInformation(context).toWhiteContainer(width: double.infinity, allPading: 12, margin: const EdgeInsets.symmetric(horizontal: 21, vertical: 4)),
              ],
            ),
          ).expand(),
          ShowFillButton(
            maxWidth: double.infinity,
            margin: const EdgeInsets.symmetric(vertical: 10, horizontal: 21),
            maxHeight: 55,
            title: LocaleKeys.payNow.tr(),
            isBold: false,
            onPressed: () {
              final requestVM = context.read<RequestsVM>();
              // context.read<PaymentVM>().updateRequestId(id: requestVM.currentSelectedRequest!.id);
              if (requestVM.selectedDeliveryOptionEnum == null) {
                requestVM.updateSelectedDeliveryOptionEnumError(GlobalConsts.deliveryOptionSelectionError);
              } else {
                navigateWithName(context, AppRoutes.paymentMethodsView, arguments: PaymentTypes.request);
              }
            },
          ),
        ],
      ),
    );
  }
}
