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/dialogs_and_bottomsheets.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/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/views/setting_options/widgets/custom_setting_options_tile.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/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>();

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

  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>();

    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,
        Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            SingleDetailWidget(text: requestVM.currentSelectedRequest!.address ?? "", type: LocaleKeys.location.tr()),
            // 16.height,
            // SingleDetailWidget(
            //   text: requestVM.additionalAddressSparePartRequestDelivery.isNotEmpty ? requestVM.additionalAddressSparePartRequestDelivery : "N/A",
            //   type: LocaleKeys.additionalAddressDetails.tr(),
            // ),
          ],
        ),
      ],
    );
  }

  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!.manufacturedById != null) ...[
                    16.height,
                    SingleDetailWidget(text: (requestVM.acceptedRequestOffer!.manufacturedById ?? "").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,
                ],
              ),
            ),
            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.currentSelectedRequest!.price.toString()} ${LocaleKeys.sar.tr()}", type: LocaleKeys.totalPrice.tr()),
                  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()),
                  ],
                ],
              ),
            ),
          ],
        ),
        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: [
                    "Update your location information".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(
                        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: () {
                              // TODO: Call some api here to update this info for this specific request.
                              requestsVM.currentSelectedRequest!.address = requestsVM.addressSparePartRequestDelivery;
                              requestsVM.updateAdditionalAddressSparePartRequestDelivery(additionalDetails);
                              requestsVM.notifyListeners();
                              pop(context);
                            },
                          ),
                        )
                      ],
                    ),
                    25.height,
                  ],
                );
              },
            ),
          ),
        );
      },
    );
  }

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

    return showModalBottomSheet(
      context: context,
      isScrollControlled: true,
      enableDrag: true,
      builder: (BuildContext context) {
        return InfoBottomSheet(
          title: LocaleKeys.contactDetails.tr().toText(fontSize: 28, isBold: true, letterSpacing: -1.44),
          description: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              if (requestVM.currentSelectedOffer!.mobileNo != null && requestVM.currentSelectedOffer!.mobileNo!.isNotEmpty) ...[
                CustomSettingOptionsTile(
                  leadingWidget: const Icon(
                    Icons.call,
                    size: 20,
                    color: MyColors.greyColor,
                  ),
                  titleText: LocaleKeys.phoneNumber.tr(),
                  subTitle: " ${requestVM.currentSelectedOffer!.mobileNo ?? ""}",
                  needBorderBelow: true,
                  showTrailingArrow: false,
                  subtitleTextColor: MyColors.greyColor,
                  onTap: () {
                    Utils.openNumberViaCaller(phoneNumber: requestVM.currentSelectedOffer!.mobileNo ?? "");
                  },
                ),
              ],
              if (requestVM.currentSelectedOffer!.email != null && requestVM.currentSelectedOffer!.email!.isNotEmpty) ...[
                CustomSettingOptionsTile(
                  leadingWidget: const Icon(
                    Icons.email_outlined,
                    size: 20,
                    color: MyColors.greyColor,
                  ),
                  titleText: LocaleKeys.emailAddress.tr(),
                  subTitle: " ${requestVM.currentSelectedOffer!.email ?? ""}",
                  needBorderBelow: false,
                  showTrailingArrow: false,
                  subtitleTextColor: MyColors.greyColor,
                  onTap: () {
                    Utils.openEmailViaEmailApp(emailAddress: requestVM.currentSelectedOffer!.email ?? "");
                  },
                ),
              ],
              30.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: () => buildProviderContactInfoBottomSheet(context),
            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: () {
              // context.read<PaymentVM>().updateRequestId(id: requestVM.currentSelectedRequest!.id);
              navigateWithName(context, AppRoutes.paymentMethodsView, arguments: PaymentTypes.request);
            },
          ),
        ],
      ),
    );
  }
}
