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/classes/consts.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/advertisment_models/ad_details_model.dart';
import 'package:mc_common_app/models/general_models/widgets_models.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/utils.dart';
import 'package:mc_common_app/view_models/ad_view_model.dart';
import 'package:mc_common_app/view_models/payment_view_model.dart';
import 'package:mc_common_app/views/advertisement/ads_detail_view/components.dart';
import 'package:mc_common_app/views/advertisement/bottom_sheets/ad_duration_selection_sheet.dart';
import 'package:mc_common_app/views/advertisement/bottom_sheets/ads_damage_part_pictures_sheet.dart';
import 'package:mc_common_app/views/advertisement/components/ads_images_corousel_widget.dart';
import 'package:mc_common_app/widgets/bottom_sheet.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 AdsDetailView extends StatefulWidget {
  final AdDetailsModel adDetails;

  const AdsDetailView({super.key, required this.adDetails});

  @override
  State<AdsDetailView> createState() => _AdsDetailViewState();
}

class _AdsDetailViewState extends State<AdsDetailView> {
  late AdVM adVM;

  @override
  void initState() {
    adVM = context.read<AdVM>();
    scheduleMicrotask(() {
      onAdDetailsLoaded();
    });
    super.initState();
  }

  Future<void> onAdDetailsLoaded() async {
    context.read<PaymentVM>().updateCurrentAdId(id: widget.adDetails.id!);
    if ((widget.adDetails.isMyAd ?? false) && (widget.adDetails.adPostStatus == AdPostStatus.reserved)) {
      await adVM.getAdBankingAccountInfo(adId: widget.adDetails.id!);
    }
  }

  void deleteAdBottomSheet(BuildContext context) {
    return actionConfirmationBottomSheet(
      context: context,
      title: LocaleKeys.deleteAdConfirmation.tr().toText(fontSize: 28, isBold: true, letterSpacing: -1.44),
      subtitle: LocaleKeys.deleteAdConfirmationMessage.tr(),
      actionButtonYes: Expanded(
        child: ShowFillButton(
          maxHeight: 55,
          title: LocaleKeys.yes.tr(),
          fontSize: 15,
          onPressed: () {
            Navigator.pop(context);
            adVM.deleteMyAd(context, adId: widget.adDetails.id!);
          },
        ),
      ),
      actionButtonNo: Expanded(
        child: ShowFillButton(
          maxHeight: 55,
          isFilled: false,
          borderColor: MyColors.darkPrimaryColor,
          title: LocaleKeys.no.tr(),
          txtColor: MyColors.darkPrimaryColor,
          fontSize: 15,
          onPressed: () {
            Navigator.pop(context);
          },
        ),
      ),
    );
  }

  Widget buildVehicleDetailsWidget() {
    return Column(
      mainAxisSize: MainAxisSize.min,
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        ImagesCorouselWidget(imagesList: widget.adDetails.vehicle!.image!),
        Row(
          mainAxisAlignment: MainAxisAlignment.spaceBetween,
          children: [
            Flexible(
              child: "${widget.adDetails.vehicle!.vehicleTitle} | ${widget.adDetails.vehicle!.color!.label}| ${widget.adDetails.id}".toText(fontSize: 16, maxLines: 2),
            ),
            (widget.adDetails.vehicle!.cityName ?? "").toText(fontSize: 10, color: MyColors.lightTextColor),
          ],
        ),
        Row(
          mainAxisAlignment: MainAxisAlignment.spaceBetween,
          children: [
            Row(
              children: [
                ("${LocaleKeys.model.tr()}: ").toText(fontSize: 12, color: MyColors.lightTextColor),
                "${widget.adDetails.vehicle!.modelyear!.label}".toText(fontSize: 12),
              ],
            ),
            "${widget.adDetails.vehicle!.countryID}".toText(fontSize: 10, color: MyColors.lightTextColor),
          ],
        ),
        Row(
          mainAxisAlignment: MainAxisAlignment.spaceBetween,
          children: [
            Row(
              children: [
                ("${LocaleKeys.mileage.tr()}: ").toText(fontSize: 12, color: MyColors.lightTextColor),
                "${widget.adDetails.vehicle!.mileage!.mileageEnd} Km".toText(fontSize: 12),
              ],
            ),
            widget.adDetails.createdOn != null ? DateTime.parse(widget.adDetails.createdOn!).getTimeAgo().toText(fontSize: 10, color: MyColors.lightTextColor) : const SizedBox(),
          ],
        ),
        Row(
          children: [
            ("${LocaleKeys.transmission.tr()}: ").toText(fontSize: 12, color: MyColors.lightTextColor),
            "${widget.adDetails.vehicle!.transmission!.label}".toText(fontSize: 12),
          ],
        ),
        Row(
          children: [
            ("${LocaleKeys.financeAvailable.tr()}: ").toText(fontSize: 12, color: MyColors.lightTextColor),
            ((widget.adDetails.vehicle!.isFinanceAvailable ?? false) ? LocaleKeys.yes.tr() : LocaleKeys.no.tr()).toText(fontSize: 12),
          ],
        ),
        8.height,
        ("${LocaleKeys.description.tr()}: ").toText(fontSize: 12, color: MyColors.lightTextColor),
        "${widget.adDetails.vehicle!.vehicleDescription}".toText(fontSize: 14),
        if (widget.adDetails.isMyAd ?? false) ...[
          8.height,
          ("${LocaleKeys.demand.tr()}: ").toText(fontSize: 12, color: MyColors.lightTextColor),
          Row(
            crossAxisAlignment: CrossAxisAlignment.end,
            children: [
              widget.adDetails.vehicle!.demandAmount!.toInt().toString().toText(fontSize: 30, height: 1.2, isBold: true),
              (widget.adDetails.vehicle!.currency ?? LocaleKeys.sar.tr()).toText(fontSize: 15, color: MyColors.lightTextColor).paddingOnly(bottom: 5),
            ],
          ),
          if (widget.adDetails.adPostStatus == AdPostStatus.expired) ...[
            8.height,
            const Divider(thickness: 1, height: 1),
            8.height,
            LocaleKeys.adDurationExpired.tr().toText(
                  color: MyColors.redColor,
                  fontSize: 12,
                  isItalic: true,
                ),
          ],
        ]
      ],
    ).toWhiteContainer(width: double.infinity, allPading: 12);
  }

  Widget showItem(String title, String value) {
    return Row(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        "$title: ".toText(color: MyColors.lightTextColor, letterSpacing: -0.48),
        3.width,
        Flexible(child: value.toText(isBold: true, overflow: TextOverflow.ellipsis)),
      ],
    );
  }

  Widget buildPersonalInformationCard({required BuildContext context}) {
    if (widget.adDetails.adOwnerDetails == null) {
      return const SizedBox();
    }
    if ((widget.adDetails.adOwnerDetails!.name == null || widget.adDetails.adOwnerDetails!.name!.isEmpty) &&
        (widget.adDetails.adOwnerDetails!.mobileNo == null || widget.adDetails.adOwnerDetails!.mobileNo!.isEmpty) &&
        (widget.adDetails.adOwnerDetails!.email == null || widget.adDetails.adOwnerDetails!.email!.isEmpty)) {
      return const SizedBox();
    }

    String name = widget.adDetails.adOwnerDetails!.name ?? "";
    String phone = widget.adDetails.adOwnerDetails!.mobileNo ?? "";
    String email = widget.adDetails.adOwnerDetails!.email ?? "";

    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      mainAxisAlignment: MainAxisAlignment.start,
      children: [
        (LocaleKeys.ownerInformation.tr()).toText(fontSize: 16),
        name.isNotEmpty ? showItem(LocaleKeys.name.tr(), "$name ") : const SizedBox(),
        phone.isNotEmpty ? showItem(LocaleKeys.phoneNumber.tr(), "$phone ") : const SizedBox(),
        email.isNotEmpty ? showItem(LocaleKeys.emailAddress.tr(), "$email ") : const SizedBox(),
      ],
    ).toWhiteContainer(width: double.infinity, allPading: 12);
  }

  Widget buildBankDetailsIfAvailable() {
    return Consumer(builder: (BuildContext context, AdVM adVM, Widget? child) {
      if (adVM.adsBankDetailsModel != null) {
        return Column(
          mainAxisSize: MainAxisSize.min,
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            LocaleKeys.bankDetails.tr().toText(fontSize: 18),
            // Row(
            //   children: [
            //     "Full Name: ".toText(fontSize: 14, isBold: true, color: MyColors.lightTextColor),
            //     "${widget.adDetails.vehicle!.vehicleDescription}".toText(
            //       fontSize: 14,
            //       isBold: true,
            //     ),
            //   ],
            // ),
            Row(
              children: [
                ("${LocaleKeys.bankName.tr()}: ").toText(fontSize: 14, color: MyColors.lightTextColor),
                (adVM.adsBankDetailsModel!.bankName ?? "").toText(fontSize: 14),
              ],
            ),
            Row(
              children: [
                ("${LocaleKeys.iban.tr()}: ").toText(fontSize: 14, color: MyColors.lightTextColor),
                (adVM.adsBankDetailsModel!.iban ?? "").toText(fontSize: 14),
              ],
            ),
          ],
        ).toWhiteContainer(width: double.infinity, allPading: 12);
      }
      return const SizedBox.shrink();
    });
  }

  Widget buildAdRejectionDetails() {
    return Column(
      mainAxisSize: MainAxisSize.min,
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Row(
          crossAxisAlignment: CrossAxisAlignment.center,
          mainAxisAlignment: MainAxisAlignment.spaceBetween,
          children: [
            LocaleKeys.rejectionComments.tr().toText(fontSize: 12),
            Row(
              children: [
                LocaleKeys.editAd.tr().toText(fontSize: 12),
                6.width,
                MyAssets.icEdit.buildSvg(height: 12).paddingOnly(bottom: 5),
              ],
            ).onPress(() async {
              Utils.showLoading(context);
              await adVM.getVehicleTypes();
              await adVM.getVehicleBrandsByVehicleTypeId(vehicleIdForEditAd: widget.adDetails.vehicle!.vehicleType ?? -1);
              Utils.hideLoading(context);
              adVM.onEditUpdateAdPressed(context: context, previousDetails: widget.adDetails, isFromExtendAd: false);
            }),
          ],
        ).paddingOnly(bottom: 5),
        Row(
          children: [
            Flexible(
              child: (widget.adDetails.comment ?? "").toText(
                color: MyColors.redColor,
                fontSize: 12,
                isItalic: true,
              ),
            )
          ],
        ),
      ],
    ).toWhiteContainer(width: double.infinity, allPading: 12);
  }

  Widget buildDamagePartDetails() {
    return Row(
      crossAxisAlignment: CrossAxisAlignment.center,
      mainAxisAlignment: MainAxisAlignment.spaceBetween,
      children: [
        Row(
          children: [
            MyAssets.carHitIcon.buildSvg(color: MyColors.darkTextColor),
            10.width,
            LocaleKeys.damagePartPictures.tr().toText(fontSize: 14),
          ],
        ),
        const Icon(Icons.arrow_forward_ios_rounded, size: 20)
      ],
    ).paddingOnly(top: 5, bottom: 5).onPress(() {
      showMyBottomSheet(context, child: AdDamagePartPicturesSheet(adDamageReportList: widget.adDetails.vehicle!.damagereport ?? []));
    }).toWhiteContainer(width: double.infinity, allPading: 12);
  }

  Future<void> onExtendAdPressed() async {
    final AdVM adVM = context.read<AdVM>();
    return actionConfirmationBottomSheet(
      context: context,
      title: LocaleKeys.updateAdDetails.tr().toText(fontSize: 28, isBold: true, letterSpacing: -1.44),
      subtitle: LocaleKeys.durationExtendingAd.tr(),
      actionButtonYes: Expanded(
        child: ShowFillButton(
          maxHeight: 55,
          title: LocaleKeys.yes.tr(),
          fontSize: 15,
          onPressed: () async {
            Utils.showLoading(context);
            await adVM.getVehicleTypes();
            await adVM.getVehicleBrandsByVehicleTypeId(vehicleIdForEditAd: widget.adDetails.vehicle!.vehicleType ?? -1);
            Utils.hideLoading(context);
            adVM.onEditUpdateAdPressed(context: context, previousDetails: widget.adDetails, isFromExtendAd: true);
          },
        ),
      ),
      actionButtonNo: Expanded(
        child: ShowFillButton(
          maxHeight: 55,
          isFilled: false,
          borderColor: MyColors.darkPrimaryColor,
          title: LocaleKeys.no.tr(),
          txtColor: MyColors.darkPrimaryColor,
          fontSize: 15,
          onPressed: () {
            adVM.updateSelectionVehicleTypeId(
              SelectionModel(selectedId: widget.adDetails.vehicle!.vehicleType!, selectedOption: (widget.adDetails.vehicle!.vehicleType!).toVehicleTypeString(), errorValue: ""),
            );

            showMyBottomSheet(context, child: AdDurationSelectionSheet(isFromExtendAd: true, isUpdateAdSelected: false, adsID: widget.adDetails.id ?? -1));
          },
        ),
      ),
    );
  }

  Widget buildAdStartEndDates() {
    String startDate = "";
    String endDate = "";

    if (widget.adDetails.startdate != null) {
      startDate = "${DateHelper.formatAsDayMonthYear(DateTime.parse(widget.adDetails.startdate!))} at ${DateHelper.formatAsTime(DateTime.parse(widget.adDetails.startdate!))}";
    }
    if (widget.adDetails.enddate != null) {
      endDate = "${DateHelper.formatAsDayMonthYear(DateTime.parse(widget.adDetails.enddate!))} at ${DateHelper.formatAsTime(DateTime.parse(widget.adDetails.enddate!))}";
    }
    return Column(
      children: [
        Row(
          children: [
            ("${LocaleKeys.startDate.tr()}: ").toText(fontSize: 12, color: MyColors.lightTextColor),
            startDate.isNotEmpty ? startDate.toText(fontSize: 10) : const SizedBox(),
          ],
        ),
        Row(
          mainAxisAlignment: MainAxisAlignment.spaceBetween,
          children: [
            Row(
              children: [
                ("${LocaleKeys.endDate.tr()}: ").toText(fontSize: 12, color: MyColors.lightTextColor),
                endDate.isNotEmpty ? endDate.toText(fontSize: 10) : const SizedBox(),
              ],
            ),
            (LocaleKeys.extendAd.tr()).toText(fontSize: 12, color: MyColors.darkPrimaryColor, isUnderLine: true).onPress(() async => await onExtendAdPressed()),
          ],
        ),
      ],
    ).paddingOnly(top: 5, bottom: 2).toWhiteContainer(width: double.infinity, allPading: 12);
  }

  @override
  Widget build(BuildContext context) {
    Widget actionWidget = const SizedBox();
    if ((widget.adDetails.isMyAd ?? false) &&
        (widget.adDetails.adPostStatus != AdPostStatus.reserved) &&
        (widget.adDetails.adPostStatus != AdPostStatus.active) &&
        (widget.adDetails.adPostStatus != AdPostStatus.pendingForPost)) {
      actionWidget = IconButton(
        icon: const Icon(Icons.delete_outline, color: MyColors.redColor),
        onPressed: () {
          return deleteAdBottomSheet(context);
        },
      );
    } else {
      actionWidget = IconButton(icon: const Icon(Icons.chat_outlined, color: Colors.black), onPressed: () => adVM.onMessagesButtonPressed(context: context, adDetailsModel: widget.adDetails));
    }
    return Scaffold(
      appBar: CustomAppBar(
        title: LocaleKeys.vehicleDetails.tr(),
        profileImageUrl: MyAssets.bnCar,
        isRemoveBackButton: false,
        isDrawerEnabled: false,
        actions: [
          actionWidget.toContainer(
            margin: const EdgeInsets.fromLTRB(0, 8, 21, 8),
            paddingAll: 0,
            borderRadius: 100,
            borderColor: MyColors.lightGreyEFColor,
            isEnabledBorder: true,
            height: 40,
            width: 42,
          ),
        ],
        onTap: () {},
      ),
      body: Container(
        padding: const EdgeInsets.only(bottom: 10, left: 21, right: 21),
        child: Column(
          children: [
            Expanded(
              child: ListView(
                shrinkWrap: true,
                children: [
                  buildVehicleDetailsWidget(),
                  12.height,
                  buildBankDetailsIfAvailable(),
                  if (widget.adDetails.vehicle!.damagereport != null && widget.adDetails.vehicle!.damagereport!.isNotEmpty) ...[
                    buildDamagePartDetails(),
                  ],
                  if (!(widget.adDetails.isMyAd ?? false)) ...[
                    12.height,
                    buildPersonalInformationCard(context: context),
                  ],
                  if (widget.adDetails.isMyAd ?? false) ...[
                    12.height,
                    buildAdStartEndDates(),
                  ],
                  12.height,
                  if (widget.adDetails.adPostStatus == AdPostStatus.rejected) ...[
                    buildAdRejectionDetails(),
                  ],
                ],
              ),
            ),
            SizedBox(
              child: Column(
                children: [
                  if (!(widget.adDetails.isMyAd ?? false)) ...[
                    const Divider(thickness: 1, height: 1),
                    const Divider(thickness: 1, height: 1),
                    18.height,
                    Row(
                      crossAxisAlignment: CrossAxisAlignment.end,
                      children: [
                        widget.adDetails.vehicle!.demandAmount!.toInt().toString().toText(fontSize: 30, isBold: true),
                        (widget.adDetails.vehicle!.currency ?? LocaleKeys.sar.tr()).toText(fontSize: 15, isBold: true, color: MyColors.lightTextColor).paddingOnly(bottom: 5),
                      ],
                    ),
                    14.height,
                  ],
                  widget.adDetails.isMyAd ?? false ? BuildAdDetailsActionButtonForMyAds(adDetailsModel: widget.adDetails) : BuildAdDetailsActionButtonForExploreAds(adDetailsModel: widget.adDetails),
                ],
              ),
            )
          ],
        ),
      ),
    );
  }
}
