import 'dart:developer';

import 'package:easy_localization/easy_localization.dart';
import 'package:flutter/material.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/ads_duration_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/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/widgets/button/show_fill_button.dart';
import 'package:mc_common_app/widgets/extensions/extensions_widget.dart';
import 'package:provider/provider.dart';

class AdDurationSelectionSheet extends StatelessWidget {
  final bool isFromExtendAd;
  final bool isUpdateAdSelected;
  final int adsID;

  const AdDurationSelectionSheet({
    super.key,
    required this.isFromExtendAd,
    required this.isUpdateAdSelected,
    required this.adsID,
  });

  @override
  Widget build(BuildContext context) {
    AdVM adVM = context.watch<AdVM>();
    return SizedBox(
      height: MediaQuery.of(context).size.height / 1.2,
      child: Column(
        children: [
          Row(
            children: [
              LocaleKeys.selectDuration.tr().toText(fontSize: 22, isBold: true).paddingOnly(top: 10, left: 21, right: 21),
            ],
          ),
          Expanded(
            child: ListView.separated(
              shrinkWrap: true,
              itemCount: adVM.vehicleAdsDurations.length,
              itemBuilder: (BuildContext context, int index) {
                AdsDurationModel adDuration = adVM.vehicleAdsDurations[index];
                return SizedBox(
                  width: double.infinity,
                  child: Row(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    mainAxisAlignment: MainAxisAlignment.start,
                    children: [
                      Expanded(
                        child: Column(
                          crossAxisAlignment: CrossAxisAlignment.start,
                          mainAxisAlignment: MainAxisAlignment.start,
                          children: [
                            ("${adDuration.days} ${LocaleKeys.daysVar.tr()}").toString().toText(fontSize: 16, isBold: true),
                            4.height,
                            "Your Ad will be active for ${adDuration.days} Days and then you will need to extend it to keep it active. ".toText(
                              fontSize: 14,
                              color: MyColors.lightTextColor,
                            ),
                            12.height,
                            LocaleKeys.adCharges.tr().toText(fontSize: 14, color: MyColors.lightTextColor, isBold: true),
                            if (adDuration.discountPercent != null && adDuration.discountPercent! > 0.0) ...[
                              Row(
                                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                                children: [
                                  Row(
                                    crossAxisAlignment: CrossAxisAlignment.end,
                                    children: [
                                      CustomPaint(
                                          painter: DiagonalLinePainter(),
                                          child: "${adDuration.price}".toText(
                                            fontSize: 20,
                                            isBold: true,
                                          )),
                                      2.width,
                                      Padding(
                                        padding: const EdgeInsets.only(bottom: 4),
                                        child: (adDuration.currency ?? LocaleKeys.sar.tr()).toText(fontSize: 10, color: MyColors.lightTextColor, isBold: true),
                                      ),
                                      14.width,
                                      "${adDuration.priceAfterDiscount}".toText(fontSize: 20, isBold: true),
                                      2.width,
                                      Padding(
                                        padding: const EdgeInsets.only(bottom: 4),
                                        child: (adDuration.currency ?? LocaleKeys.sar.tr()).toText(fontSize: 10, color: MyColors.lightTextColor, isBold: true),
                                      ),
                                    ],
                                  ),
                                  "${adDuration.discountPercent} % OFF".toText(color: MyColors.white, fontSize: 10).toContainer(
                                        marginAll: 5,
                                        paddingAll: 5,
                                        borderRadius: 4,
                                        backgroundColor: MyColors.greenColor,
                                      ),
                                ],
                              ),
                            ] else ...[
                              Row(
                                crossAxisAlignment: CrossAxisAlignment.end,
                                children: [
                                  "${adDuration.price}".toText(fontSize: 22, isBold: true),
                                  2.width,
                                  Padding(
                                    padding: const EdgeInsets.only(bottom: 4),
                                    child: (adDuration.currency ?? LocaleKeys.sar.tr()).toText(fontSize: 12, color: MyColors.lightTextColor, isBold: true),
                                  ),
                                ],
                              ),
                            ]
                          ],
                        ),
                      ),
                    ],
                  ).toWhiteContainer(
                    width: double.infinity,
                    allPading: 12,
                    isBorderRequired: adDuration.id == adVM.vehicleAdDurationId.selectedId,
                  ),
                ).onPress(() {
                  if (isFromExtendAd) {
                    adVM.updateVehicleExtendAdDurationId(
                      SelectionModel(
                        selectedId: adDuration.id ?? 0,
                        selectedOption: ("${adDuration.days} ${LocaleKeys.daysVar.tr()}"),
                        itemPrice: adDuration.priceAfterDiscount!.toInt().toString(),
                      ),
                    );
                    return;
                  }
                  adVM.updateVehicleAdDurationId(
                    SelectionModel(
                      selectedId: adDuration.id ?? 0,
                      selectedOption: ("${adDuration.days} ${LocaleKeys.daysVar.tr()}"),
                      itemPrice: adDuration.priceAfterDiscount!.toString(),
                      currency: adDuration.currency!.toString(),
                    ),
                  );
                });
              },
              separatorBuilder: (BuildContext context, int index) {
                return 12.height;
              },
              padding: const EdgeInsets.all(20),
            ),
          ),
          ShowFillButton(
            iconWidget: adVM.isFetchingLists
                ? const Padding(
                    padding: EdgeInsets.all(8.0),
                    child: SizedBox(
                      height: 30,
                      width: 30,
                      child: CircularProgressIndicator(color: Colors.white),
                    ),
                  )
                : null,
            title: adVM.isFetchingLists ? "" : LocaleKeys.select.tr(),
            maxWidth: double.infinity,
            margin: const EdgeInsets.all(21),
            onPressed: () async {
              if (adVM.isFetchingLists) {
                return;
              } else {
                if (isFromExtendAd && !isUpdateAdSelected) {
                  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);
                }
              }
            },
          ).toContainer(paddingAll: 0, backgroundColor: Colors.white),
        ],
      ),
    );
  }

  Widget showItem(String item, String value, {Color valueColor = Colors.black}) {
    return Row(
      crossAxisAlignment: CrossAxisAlignment.start,
      mainAxisAlignment: MainAxisAlignment.start,
      children: [
        item.toText(fontSize: 12, color: MyColors.lightTextColor, isBold: true),
        4.width,
        value.toText(fontSize: 12, color: valueColor, isBold: true),
      ],
    );
  }
}

class DiagonalLinePainter extends CustomPainter {
  @override
  void paint(Canvas canvas, Size size) {
    final Paint paint = Paint()
      ..color = MyColors.redColor
      ..strokeWidth = 2.5;

    // Draw the diagonal line from top-left to bottom-right
    canvas.drawLine(const Offset(0, 0), Offset(size.width, size.height), paint);
  }

  @override
  bool shouldRepaint(CustomPainter oldDelegate) {
    return false;
  }
}
