import 'dart:developer';
import 'dart:ui';

import 'package:easy_localization/easy_localization.dart';
import 'package:flutter/material.dart';
import 'package:flutter_svg/flutter_svg.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/ad_details_model.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/utils/utils.dart';
import 'package:mc_common_app/view_models/ad_view_model.dart';
import 'package:mc_common_app/widgets/extensions/extensions_widget.dart';
import 'package:provider/provider.dart';

import '../../../classes/app_state.dart';

class AdsListWidget extends StatelessWidget {
  final List<AdDetailsModel> adsList;
  final ScrollPhysics? scrollPhysics;
  final bool isAdsFragment;
  final bool shouldShowAdStatus;
  final bool hasMoreData;
  final bool isDraftAds;
  final Function()? onFetchMoreAds;

  const AdsListWidget({
    super.key,
    required this.adsList,
    required this.shouldShowAdStatus,
    required this.hasMoreData,
    required this.isDraftAds,
    this.onFetchMoreAds,
    this.scrollPhysics,
    this.isAdsFragment = false,
  });

  @override
  Widget build(BuildContext context) {
    final adVM = context.watch<AdVM>();

    if (isAdsFragment && adsList.isEmpty) {
      return Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          const SizedBox(height: 25),
          (adVM.adsFiltersCounter > 0 ? "No Ads that matches your search" : LocaleKeys.noAdsShow.tr()).toText(fontSize: 16, color: MyColors.lightTextColor, fontWeight: MyFonts.Medium),
          if (adVM.adsFiltersCounter > 0) ...[
            const SizedBox(height: 16),
            GestureDetector(
              onTap: () {
                adVM.clearAdsFilters();
              },
              child: Text(
                LocaleKeys.clearFilters.tr(),
                style: const TextStyle(
                  color: MyColors.darkPrimaryColor,
                  fontSize: 18,
                  fontWeight: FontWeight.w600,
                ),
              ),
            ),
          ],
        ],
      );
    }
    return NotificationListener<ScrollNotification>(
      onNotification: (ScrollNotification scrollInfo) {
        if (scrollInfo.metrics.pixels == scrollInfo.metrics.maxScrollExtent && hasMoreData) {
          if (onFetchMoreAds != null) {
            onFetchMoreAds!();
          }
        }
        return false;
      },
      child: ListView.separated(
        itemCount: adsList.length,
        shrinkWrap: true,
        physics: scrollPhysics,
        itemBuilder: (BuildContext context, int index) {
          return AdCard(
            adDetails: adsList[index],
            isAdsFragment: isAdsFragment,
            shouldShowAdStatus: shouldShowAdStatus,
          ).onPress(
            () {
              if (isDraftAds) {
                context.read<AdVM>().onEditUpdateAdPressed(
                      context: context,
                      previousDetails: adsList[index],
                      isFromExtendAd: false,
                      isForDraft: true,
                    );
              } else {
                navigateWithName(context, AppRoutes.adsDetailView, arguments: adsList[index]);
              }
            },
          ).toViewOnly(context, onTap: () => navigateWithName(context, AppRoutes.loginWithPassword, arguments: false));
        },
        separatorBuilder: (BuildContext context, int index) {
          return 12.height;
        },
        padding: const EdgeInsets.symmetric(horizontal: 21),
      ),
    );
  }
}

class AdCard extends StatefulWidget {
  final AdDetailsModel adDetails;
  final bool isAdsFragment;
  final bool shouldShowAdStatus;
  final bool needBorder;

  const AdCard({
    super.key,
    required this.adDetails,
    required this.isAdsFragment,
    required this.shouldShowAdStatus,
    this.needBorder = true,
  });

  @override
  State<AdCard> createState() => _AdCardState();
}

class _AdCardState extends State<AdCard> {
  int _currentImageIndex = 0;
  late PageController _pageController;

  @override
  void initState() {
    super.initState();
    _pageController = PageController();
  }

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

  @override
  Widget build(BuildContext context) {
    bool isArabic = AppState().isArabic(context);
    final bool hasMultipleImages = widget.adDetails.vehicle?.image?.length == null
        ? false
        : (widget.adDetails.vehicle?.image?.length == 0 || widget.adDetails.vehicle?.image?.length == 1)
            ? false
            : true;
    final isAdsFragment = widget.isAdsFragment;

    return Stack(
      alignment: Alignment.center,
      children: [
        if (widget.adDetails.vehicle == null) ...[
          Expanded(
            child: Column(
              children: [
                "Ad format needs to be updated.".toText(),
              ],
            ),
          ),
        ] else ...[
          Row(
            children: [
              Stack(
                alignment: Alignment.center,
                children: [
                  ClipRRect(
                    child: SizedBox(
                      width: 100,
                      height: 100,
                      child: hasMultipleImages
                          ? PageView.builder(
                              controller: _pageController,
                              itemCount: widget.adDetails.vehicle!.image!.length,
                              onPageChanged: (index) {
                                setState(() {
                                  _currentImageIndex = index;
                                });
                              },
                              itemBuilder: (context, index) {
                                return widget.adDetails.vehicle!.image![index].imageUrl.buildNetworkImage(
                                  width: 100,
                                  height: 100,
                                  fit: BoxFit.cover,
                                );
                              },
                            )
                          : widget.adDetails.vehicle!.image!.first.imageUrl.buildNetworkImage(
                              width: 100,
                              height: 100,
                              fit: BoxFit.cover,
                            ),
                    ),
                  ),
                  // Image indicator dots
                  if (hasMultipleImages)
                    Positioned(
                      bottom: 6,
                      child: Container(
                        padding: const EdgeInsets.symmetric(horizontal: 6, vertical: 4),
                        decoration: BoxDecoration(
                          color: Colors.black.withOpacity(0.4),
                          borderRadius: BorderRadius.circular(12),
                        ),
                        child: Row(
                          mainAxisAlignment: MainAxisAlignment.center,
                          mainAxisSize: MainAxisSize.min,
                          children: List.generate(
                            widget.adDetails.vehicle!.image!.length,
                            (index) => Container(
                              width: 6,
                              height: 6,
                              margin: const EdgeInsets.symmetric(horizontal: 3),
                              decoration: BoxDecoration(
                                shape: BoxShape.circle,
                                color: _currentImageIndex == index ? Colors.white : Colors.white.withOpacity(0.5),
                                border: Border.all(
                                  color: Colors.black.withOpacity(0.2),
                                  width: 0.5,
                                ),
                              ),
                            ),
                          ),
                        ),
                      ),
                    ),
                  if (widget.adDetails.adPostStatus == AdPostStatus.sold) ...[
                    // Blur overlay
                    ClipRRect(
                      borderRadius: BorderRadius.circular(8),
                      child: BackdropFilter(
                        filter: ImageFilter.blur(sigmaX: 3, sigmaY: 3),
                        child: Container(
                          width: 100,
                          height: 100,
                          color: Colors.black.withOpacity(0.3),
                        ),
                      ),
                    ),
                    // SOLD text
                    Container(
                      padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 4),
                      decoration: BoxDecoration(
                        color: Colors.red,
                        borderRadius: BorderRadius.circular(4),
                      ),
                      child: LocaleKeys.sold.tr().toText(
                            fontSize: 12,
                            color: Colors.white,
                            isBold: true,
                          ),
                    ),
                  ],
                ],
              ),
              12.width,
              Expanded(
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Row(
                      mainAxisAlignment: MainAxisAlignment.start,
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        Expanded(
                          child: Column(
                            crossAxisAlignment: CrossAxisAlignment.start,
                            mainAxisAlignment: MainAxisAlignment.start,
                            children: [
                              // if (isAdsFragment && adDetails.adPostStatus! == AdPostStatus.sold && adDetails.statuslabel != null && adDetails.statuslabel!.isNotEmpty) ...[
                              //   Utils.statusContainerChip(text: adDetails.statuslabel ?? "", chipColor: Utils.getChipColorByAdStatus(adDetails.adPostStatus!)),
                              // ] else if (isAdsFragment && !context.read<AdVM>().isExploreAdsTapped && adDetails.statuslabel != null && adDetails.statuslabel!.isNotEmpty) ...[
                              //   Utils.statusContainerChip(text: adDetails.statuslabel ?? "", chipColor: Utils.getChipColorByAdStatus(adDetails.adPostStatus!)),
                              // ],
                              if (isAdsFragment &&
                                  widget.adDetails.adPostStatus! == AdPostStatus.sold &&
                                  widget.adDetails.statuslabel != null &&
                                  widget.adDetails.statuslabel!.isNotEmpty) ...[
                                Utils.statusContainerChip(
                                  text: isArabic
                                      ? (widget.adDetails.statuslabelN ?? "")
                                      : (widget.adDetails.statuslabel ?? ""),
                                  chipColor: Utils.getChipColorByAdStatus(widget.adDetails.adPostStatus!),
                                ),
                              ] else if (isAdsFragment &&
                                  !context.read<AdVM>().isExploreAdsTapped &&
                                  widget.adDetails.statuslabel != null &&
                                  widget.adDetails.statuslabel!.isNotEmpty) ...[
                                Utils.statusContainerChip(
                                  text: isArabic
                                      ? (widget.adDetails.statuslabelN ?? "")
                                      : (widget.adDetails.statuslabel ?? ""),
                                  chipColor: Utils.getChipColorByAdStatus(widget.adDetails.adPostStatus!),
                                ),
                              ],
                              // Show Accident Free chip for explore ads when isAccidentFree is true
                              if (isAdsFragment && context.read<AdVM>().isExploreAdsTapped && widget.adDetails.vehicle?.isAccidentFree == true) ...[
                                Utils.statusContainerChip(text: LocaleKeys.accidentFree.tr(), chipColor: Colors.green),
                              ],
                              (widget.adDetails.vehicle!.vehicleTitle ?? "").toText(
                                fontSize: 16,
                                letterSpacing: -0.64,
                                height: 25 / 16,
                              ),
                              Row(
                                children: [
                                  ("${LocaleKeys.model.tr()}:").toText(
                                    fontSize: 12,
                                    color: MyColors.lightTextColor,
                                    letterSpacing: -0.48,
                                    height: 18 / 12,
                                  ),
                                  2.width,
                                  (widget.adDetails.vehicle!.modelyear!.label ?? "").toText(
                                    fontSize: 12,
                                    letterSpacing: -0.48,
                                    height: 18 / 12,
                                  ),
                                ],
                              ),
                              Row(
                                children: [
                                  ("${LocaleKeys.mileage.tr()}:").toText(
                                    color: MyColors.lightTextColor,
                                    fontSize: 12,
                                    letterSpacing: -0.48,
                                    height: 18 / 12,
                                  ),
                                  2.width,
                                  (widget.adDetails.vehicle!.mileage!.mileageEnd ?? "").toText(
                                    fontSize: 12,
                                    letterSpacing: -0.48,
                                    height: 18 / 12,
                                  ),
                                ],
                              ),
                            ],
                          ),
                        ),
                        Column(
                          crossAxisAlignment: CrossAxisAlignment.end,
                          mainAxisAlignment: MainAxisAlignment.start,
                          children: [
                            (widget.adDetails.vehicle!.cityName ?? "").toText(color: MyColors.lightTextColor),
                            widget.adDetails.createdOn != null ? DateTime.parse(widget.adDetails.createdOn!).getTimeAgo().toText(color: MyColors.lightTextColor) : const SizedBox(),
                          ],
                        ),
                      ],
                    ),
                    8.height,
                    Row(
                      children: [
                        Expanded(
                          child: Row(
                            mainAxisAlignment: MainAxisAlignment.start,
                            crossAxisAlignment: CrossAxisAlignment.end,
                            children: [
                              (widget.adDetails.vehicle!.demandAmount!.toInt().toString()).toText(fontSize: 19, isBold: true, letterSpacing: -1.16, height: 29 / 19),
                              2.width,
                              (widget.adDetails.vehicle!.currency ?? "").toText(color: MyColors.lightTextColor, fontSize: 10, letterSpacing: -0.4, height: 16 / 10).paddingOnly(bottom: 3),
                            ],
                          ),
                        ),
                        SvgPicture.asset(
                          MyAssets.arrowRight,
                          height: 9.69,
                          width: 13,
                        ),

                        //   const Icon(Icons.arrow_forward)
                      ],
                    ),
                  ],
                ),
              ),
            ],
          ),
        ],
        if (false)
          Container(
            height: 100,
            alignment: Alignment.center,
            color: MyColors.white.withOpacity(0.9),
            child: Row(
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                MyAssets.reservedConeIcon.buildSvg(),
                5.width,
                "Reserved".toText(
                  color: MyColors.darkPrimaryColor,
                  fontSize: 17,
                  isBold: true,
                )
              ],
            ),
          )
        else
          const SizedBox(),
      ],
    ).toWhiteContainer(
      width: double.infinity,
      allPading: 12,
      isBorderRequired: widget.needBorder,
    );
  }
}
