import 'dart:developer';

import 'package:flutter/gestures.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/advertisment_models/vehicle_details_models.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/enums.dart';
import 'package:mc_common_app/utils/navigator.dart';
import 'package:mc_common_app/view_models/ad_view_model.dart';
import 'package:mc_common_app/views/advertisement/ads_buyer_chats_view.dart';
import 'package:mc_common_app/views/advertisement/bottom_sheets/ad_duration_selection_sheet.dart';
import 'package:mc_common_app/widgets/bottom_sheet.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 SelectAdTypeView extends StatelessWidget {
  final List<dynamic> arguments; // [0] isProviderOrCustomer    [1] isFromExtendAd

  const SelectAdTypeView({super.key, required this.arguments});

  Widget getVehicleAdTypeIcon(VehicleType vehicleTypeEnum) {
    switch (vehicleTypeEnum) {
      case VehicleType.car:
        return MyAssets.vehicleTypeCar.buildSvg(height: 22);

      case VehicleType.motorCycle:
        return MyAssets.vehicleTypeMotorcycle.buildSvg(height: 26);

      case VehicleType.golfCart:
        return MyAssets.vehicleTypeGolfCart.buildSvg(height: 26);

      case VehicleType.buggy:
        return MyAssets.vehicleTypeBuggy.buildSvg(height: 26);
    }
  }

  @override
  Widget build(BuildContext context) {
    bool isProvider = arguments[0];
    bool isFromExtendAd = arguments[1];
    int adsId = -1;
    if (arguments.length > 2) {
      adsId = arguments[2] ?? -1;
    }

    int totalAds = 0;
    int remainingAds = 0;

    if (AppState().getproviderSubscription.isNotEmpty && AppState().getproviderSubscription.first.adsRemaining != null) {
      totalAds = AppState().getproviderSubscription.first.totalAds ?? 0;
      remainingAds = AppState().getproviderSubscription.first.adsRemaining ?? 0;
    }
    return Scaffold(
      appBar: CustomAppBar(
        title: LocaleKeys.selectAdType.tr(),
        profileImageUrl: MyAssets.bnCar,
        isRemoveBackButton: false,
        isDrawerEnabled: false,
      ),
      body: Column(
        children: [
          Expanded(
            child: Consumer(builder: (BuildContext context, AdVM adVM, Widget? child) {
              return ListView.separated(
                itemCount: adVM.vehicleTypes.length,
                itemBuilder: (BuildContext context, int index) {
                  VehicleTypeModel vehicleTypeModel = adVM.vehicleTypes[index];
                  return InkWell(
                    onTap: () async {
                      adVM.updateSelectionVehicleTypeId(SelectionModel(selectedId: vehicleTypeModel.id!, selectedOption: vehicleTypeModel.vehicleTypeName ?? "", errorValue: ""));
                      if (adVM.isAdEditEnabled) {
                        adVM.autoFillSelectedVehicleAdsDetails();
                      }
                      if (AppState().currentAppType == AppType.provider && AppState().userType == UserType.providerDealer) {
                        if (isFromExtendAd && !adVM.isAdEditEnabled) {
                          bool status = await adVM.createAdExtensionOrder(context, adId: adsId, adsDurationId: adVM.vehicleAdDurationId.selectedId);
                          log("hereStatus: $status");
                          if (status) {
                            navigateWithName(context, AppRoutes.paymentMethodsView, arguments: PaymentTypes.extendAds);
                          }
                        } else {
                          navigateReplaceWithName(context, AppRoutes.createAdView);
                        }
                      } else {
                        showMyBottomSheet(context, child: AdDurationSelectionSheet(isUpdateAdSelected: adVM.isAdEditEnabled, isFromExtendAd: isFromExtendAd, adsID: adsId));
                      }
                    },
                    child: SizedBox(
                      width: double.infinity,
                      child: Row(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        mainAxisAlignment: MainAxisAlignment.start,
                        children: [
                          Expanded(
                            child: Column(
                              crossAxisAlignment: CrossAxisAlignment.start,
                              mainAxisAlignment: MainAxisAlignment.start,
                              children: [
                                Row(
                                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                                  children: [
                                    vehicleTypeModel.vehicleTypeName.toString().toText(fontSize: 18),
                                    getVehicleAdTypeIcon(vehicleTypeModel.vehicleTypeEnum!),
                                  ],
                                ),
                                if (isProvider) ...[
                                  Row(
                                    children: [
                                      "${LocaleKeys.duration.tr()}: ".toText(fontSize: 12, color: MyColors.lightTextColor, isBold: true),
                                      2.width,
                                      LocaleKeys.validUntilSubscriptionExpiration.tr().toText(fontSize: 13),
                                    ],
                                  ).paddingOnly(top: 5, bottom: 5),
                                ] else ...[
                                  Row(
                                    children: [
                                      LocaleKeys.duration.tr().toText(fontSize: 12, color: MyColors.lightTextColor, isBold: true),
                                      4.width,
                                      adVM.vehicleAdDurationId.selectedOption.toText(fontSize: 13, isBold: true),
                                      const Icon(Icons.keyboard_arrow_down_sharp, color: MyColors.darkPrimaryColor, size: 20),
                                    ],
                                  ).paddingOnly(top: 5, bottom: 5),
                                ],
                                if (!isProvider) ...[
                                  Row(
                                    crossAxisAlignment: CrossAxisAlignment.end,
                                    children: [
                                      adVM.vehicleAdDurationId.itemPrice.toText(fontSize: 22, isBold: true),
                                      2.width,
                                      Padding(
                                        padding: const EdgeInsets.only(bottom: 4),
                                        child: adVM.vehicleAdDurationId.currency.toText(fontSize: 12, color: MyColors.lightTextColor, isBold: true),
                                      ),
                                    ],
                                  ),
                                ],
                              ],
                            ),
                          ),
                        ],
                      ),
                    ).toWhiteContainer(width: double.infinity, isBorderRequired: vehicleTypeModel.isSelected! ? true : false, pading: const EdgeInsets.symmetric(horizontal: 20, vertical: 10)),
                  );
                },
                separatorBuilder: (BuildContext context, int index) {
                  return 9.height;
                },
                padding: const EdgeInsets.all(20),
              );
            }),
          ),
          if (isProvider) ...[
            Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Row(
                  children: [
                    "$remainingAds ".toText(fontSize: 29, isBold: true, letterSpacing: 0, height: 1),
                    LocaleKeys.adsRemaining.tr().toText(fontSize: 17, color: MyColors.lightTextColor),
                  ],
                ),
                Text.rich(
                  TextSpan(
                    children: [
                      TextSpan(
                        text: LocaleKeys.youLeftAdsGivenSubscription.tr(),
                        style: const TextStyle(
                          fontSize: 14,
                          color: MyColors.lightTextColor,
                        ),
                      ),
                      TextSpan(
                        text: "  ${LocaleKeys.updateSubscription.tr()}",
                        recognizer: TapGestureRecognizer()
                          ..onTap = () {
                            navigateWithName(context, AppRoutes.mySubscriptionsPage);
                          },
                        style: const TextStyle(
                          decoration: TextDecoration.underline,
                          fontSize: 14,
                          fontWeight: FontWeight.w600,
                          color: MyColors.darkPrimaryColor,
                        ),
                      )
                    ],
                  ),
                ),
                10.height,
              ],
            ).toContainer(paddingAll: 20, backgroundColor: Colors.white),
          ]
        ],
      ),
    );
  }
}
