import 'dart:async';

import 'package:easy_localization/easy_localization.dart';
import 'package:flutter/material.dart';
import 'package:flutter_staggered_animations/flutter_staggered_animations.dart';
import 'package:hmg_patient_app_new/core/app_assets.dart';
import 'package:hmg_patient_app_new/core/app_state.dart';
import 'package:hmg_patient_app_new/core/dependencies.dart';
import 'package:hmg_patient_app_new/core/enums.dart';
import 'package:hmg_patient_app_new/core/utils/size_utils.dart';
import 'package:hmg_patient_app_new/core/utils/utils.dart';
import 'package:hmg_patient_app_new/extensions/widget_extensions.dart';
import 'package:hmg_patient_app_new/features/offers_and_discounts/offers_and_discounts_view_model.dart';
import 'package:hmg_patient_app_new/generated/locale_keys.g.dart';
import 'package:hmg_patient_app_new/presentation/offers_and_discounts/offers_and_discounts_detailed_page.dart';
import 'package:hmg_patient_app_new/presentation/offers_and_discounts/offers_and_discounts_history_page.dart';
import 'package:hmg_patient_app_new/presentation/offers_and_discounts/widgets/offers_and_discount_type_selection_widget.dart';
import 'package:hmg_patient_app_new/theme/colors.dart';
import 'package:hmg_patient_app_new/widgets/appbar/collapsing_list_view.dart';
import 'package:hmg_patient_app_new/widgets/buttons/custom_button.dart';
import 'package:hmg_patient_app_new/widgets/chip/app_custom_chip_widget.dart';
import 'package:hmg_patient_app_new/widgets/routes/custom_page_route.dart';
import 'package:provider/provider.dart';

import '../../widgets/input_widget.dart';

class OffersAndDiscountsPage extends StatefulWidget {
  const OffersAndDiscountsPage({super.key});

  @override
  State<OffersAndDiscountsPage> createState() => _OffersAndDiscountsPageState();
}

class _OffersAndDiscountsPageState extends State<OffersAndDiscountsPage> {
  late OffersAndDiscountsViewModel offersAndDiscountsViewModel;
  late AppState appState;
  final TextEditingController _searchController = TextEditingController();

  @override
  void initState() {
    scheduleMicrotask(() {
      offersAndDiscountsViewModel.initOffersAndDiscounts();
    });
    super.initState();
  }

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


  @override
  Widget build(BuildContext context) {
    appState = getIt.get<AppState>();
    offersAndDiscountsViewModel = Provider.of<OffersAndDiscountsViewModel>(context, listen: false);

    return CollapsingListView(
      title: "${LocaleKeys.offers.tr(context: context)} & ${LocaleKeys.discount.tr(context: context)}",
      history: () {
        Navigator.of(context).push(
          CustomPageRoute(
            page: OffersAndDiscountsHistoryPage(),
          ),
        );
      },
      child: SingleChildScrollView(
        child: Consumer<OffersAndDiscountsViewModel>(builder: (context, offersAndDiscountVM, child) {
          return Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              // Search Input
              TextInputWidget(
                labelText: LocaleKeys.search.tr(context: context),
                hintText: LocaleKeys.search.tr(context: context),
                controller: _searchController,
                onChange: (value) {
                  offersAndDiscountVM.setSearchQuery(value!);
                },
                isEnable: true,
                prefix: null,
                autoFocus: false,
                isBorderAllowed: false,
                keyboardType: TextInputType.text,
                isAllowLeadingIcon: true,
                selectionType: SelectionTypeEnum.search,
                padding: EdgeInsets.symmetric(
                  vertical: ResponsiveExtension(10).h,
                  horizontal: ResponsiveExtension(15).h,
                ),
              ),
              SizedBox(height: 16.h),
              OffersAndDiscountTypeSelectionWidget(
                selectedOffers: offersAndDiscountVM.selectedFacilities,
                onOfferClicked: (selectedValues) {
                  offersAndDiscountVM.setSelectedFacility(selectedValues);
                },
              ),

              SizedBox(height: 16.h),

              // Offers Grid
              offersAndDiscountVM.isOffersLoading
                  ? GridView.builder(
                      padding: EdgeInsets.symmetric(horizontal: 24.w),
                      shrinkWrap: true,
                      physics: NeverScrollableScrollPhysics(),
                      gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
                        crossAxisCount: 2,
                        crossAxisSpacing: 16.w,
                        mainAxisSpacing: 16.h,
                        childAspectRatio: 0.55, // Adjust this to control card height
                      ),
                      itemCount: 6,
                      // Show 6 loading placeholders
                      itemBuilder: (context, index) {
                        return Container(
                          decoration: RoundedRectangleBorder().toSmoothCornerDecoration(
                            color: AppColors.whiteColor,
                            borderRadius: 24.h,
                            hasShadow: true,
                          ),
                          child: Center(child: Utils.getLoadingWidget()),
                        );
                      },
                    )
                  : offersAndDiscountVM.filteredOffers.isNotEmpty
                      ? GridView.builder(
                          padding: EdgeInsets.symmetric(horizontal: 0.w),
                          shrinkWrap: true,
                          physics: NeverScrollableScrollPhysics(),
                          gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(crossAxisCount: 2, crossAxisSpacing: 16.w, mainAxisSpacing: 16.h, childAspectRatio: 0.55),
                          itemCount: offersAndDiscountVM.filteredOffers.length,
                          itemBuilder: (context, index) {
                            return AnimationConfiguration.staggeredGrid(
                              position: index,
                              duration: const Duration(milliseconds: 500),
                              columnCount: 2,
                              child: ScaleAnimation(
                                child: FadeInAnimation(
                                  child: AnimatedContainer(
                                    duration: Duration(milliseconds: 300),
                                    curve: Curves.easeInOut,
                                    decoration: RoundedRectangleBorder().toSmoothCornerDecoration(
                                      color: AppColors.whiteColor,
                                      borderRadius: 24.h,
                                      hasShadow: true,
                                    ),
                                    child: Column(
                                      crossAxisAlignment: CrossAxisAlignment.start,
                                      children: [
                                        if (offersAndDiscountVM.filteredOffers[index].imageUrl != null)
                                          Expanded(
                                            flex: 3,
                                            child: Stack(
                                              children: [
                                                ClipRRect(
                                                  borderRadius: BorderRadius.vertical(top: Radius.circular(24.h)),
                                                  child: SizedBox.expand(
                                                    child: Utils.buildImgWithNetwork(
                                                      url: offersAndDiscountVM.filteredOffers[index].imageUrl!,
                                                      iconColor: AppColors.blackBgColor,
                                                      fit: BoxFit.cover,
                                                      errorBuilder: (context, error, stackTrace) {
                                                        return Container(
                                                          color: AppColors.greyColor,
                                                          child: Center(
                                                            child: Icon(Icons.image_not_supported, size: 32.h),
                                                          ),
                                                        );
                                                      },
                                                    ),
                                                  ),
                                                ).onPress(() {
                                                  Navigator.of(context).push(
                                                    CustomPageRoute(
                                                      page: OffersAndDiscountsDetailedPage(
                                                        offer: offersAndDiscountVM.filteredOffers[index],
                                                      ),
                                                    ),
                                                  );
                                                }),
                                                // Discount badge at top right
                                                // if (offersAndDiscountVM.filteredOffers[index].discount != null)
                                                //   Positioned(
                                                //     top: 8.h,
                                                //     right: 8.w,
                                                //     child: Container(
                                                //       padding: EdgeInsets.symmetric(horizontal: 8.w, vertical: 4.h),
                                                //       decoration: BoxDecoration(
                                                //         color: AppColors.primaryRedColor,
                                                //         borderRadius: BorderRadius.circular(6.r),
                                                //       ),
                                                //       child: Text(
                                                //         offersAndDiscountVM.filteredOffers[index].discount!,
                                                //         style: TextStyle(
                                                //           fontSize: 10.f,
                                                //           fontWeight: FontWeight.w700,
                                                //           color: AppColors.whiteColor,
                                                //         ),
                                                //       ),
                                                //     ),
                                                //   ),
                                              ],
                                            ),
                                          ),
                                        Expanded(
                                          flex: 3,
                                          child: Padding(
                                            padding: EdgeInsets.all(12.h),
                                            child: Column(
                                              crossAxisAlignment: CrossAxisAlignment.start,
                                              mainAxisSize: MainAxisSize.min,
                                              children: [
                                                if (offersAndDiscountVM.filteredOffers[index].title != null)
                                                  Text(
                                                    offersAndDiscountVM.filteredOffers[index].title!,
                                                    style: TextStyle(
                                                      fontSize: 14.f,
                                                      fontWeight: FontWeight.w700,
                                                      color: AppColors.textColor,
                                                    ),
                                                    maxLines: 2,
                                                    overflow: TextOverflow.ellipsis,
                                                  ),
                                                SizedBox(height: 8.h),
                                                // Valid till chip
                                                if (offersAndDiscountVM.filteredOffers[index].endDate != null)
                                                  AppCustomChipWidget(
                                                    labelText: "Valid till ${Utils.formatDateToDisplay(offersAndDiscountVM.filteredOffers[index].endDate ?? "")}",
                                                    // labelText: "Valid till ${_formatDateString(offersAndDiscountVM.filteredOffers[index].endDate)}",
                                                    backgroundColor: AppColors.chipBgColor,
                                                    textColor: AppColors.textColor,
                                                    icon: AppAssets.calendar,
                                                    iconSize: 12.h,
                                                    iconColor: AppColors.textColor,
                                                    isEnglishOnly: true,
                                                    labelPadding: EdgeInsetsDirectional.only(start: 4.w, end: 8.w),
                                                  ),
                                                SizedBox(height: 20.h),
                                                CustomButton(
                                                  text: 'Buy Now',
                                                  icon: AppAssets.shoppingCart,
                                                  iconColor: AppColors.whiteColor,
                                                  onPressed: () {
                                                    // Handle buy now action
                                                  },
                                                  backgroundColor: AppColors.primaryRedColor,
                                                  borderColor: AppColors.primaryRedColor,
                                                  textColor: AppColors.whiteColor,
                                                  fontSize: 14.f,
                                                  isBold: true,
                                                  borderRadius: 12.r,
                                                  height: 40.h,
                                                ),
                                              ],
                                            ),
                                          ),
                                        ),
                                      ],
                                    ),
                                  ),
                                ),
                              ),
                            );
                          },
                        )
                      : Padding(
                          padding: EdgeInsets.symmetric(horizontal: 24.w),
                          child: Utils.getNoDataWidget(context, noDataText: LocaleKeys.noDataAvailable.tr(context: context)),
                        ),
              SizedBox(height: 24.h),
            ],
          ).paddingSymmetrical(24.h, 0.h);
        }),
      ),
    );
  }
}
