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/utils/size_utils.dart';
import 'package:hmg_patient_app_new/core/utils/utils.dart';
import 'package:hmg_patient_app_new/extensions/string_extensions.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/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';

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

  @override
  State<OffersAndDiscountsHistoryPage> createState() => _OffersAndDiscountsHistoryPageState();
}

class _OffersAndDiscountsHistoryPageState extends State<OffersAndDiscountsHistoryPage> {
  late OffersAndDiscountsViewModel offersAndDiscountsViewModel;
  late AppState appState;

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

  String _formatDateString(String? dateString) {
    if (dateString == null || dateString.isEmpty) return '';
    try {
      DateTime date = DateTime.parse(dateString);
      return DateFormat('d MMM, yyyy').format(date);
    } catch (e) {
      return dateString;
    }
  }

  // Determine the status of the offer based on dates and isActive flag
  String _getOfferStatus(String? endDate, bool? isActive) {
    if (endDate == null || endDate.isEmpty) return 'Expired';
    try {
      DateTime end = DateTime.parse(endDate);
      DateTime now = DateTime.now();

      if (now.isAfter(end)) {
        return 'Expired';
      } else {
        // If end date is in future, check isActive flag
        if (isActive == true) {
          return 'Active';
        } else {
          return 'Availed';
        }
      }
    } catch (e) {
      return 'Expired';
    }
  }

  Color _getStatusBgColor(String status) {
    switch (status) {
      case 'Active':
        return AppColors.successColor.withValues(alpha: 0.1);
      case 'Availed':
        return AppColors.infoColor.withValues(alpha: 0.1);
      case 'Expired':
        return AppColors.errorColor.withValues(alpha: 0.1);
      default:
        return AppColors.greyColor;
    }
  }

  Color _getStatusTextColor(String status) {
    switch (status) {
      case 'Active':
        return AppColors.successColor;
      case 'Availed':
        return AppColors.infoColor;
      case 'Expired':
        return AppColors.errorColor;
      default:
        return AppColors.textColor;
    }
  }

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

    return CollapsingListView(
      title: '${LocaleKeys.order.tr(context: context)} ${LocaleKeys.history.tr(context: context)}',
      child: SingleChildScrollView(
        child: Consumer<OffersAndDiscountsViewModel>(builder: (context, offersAndDiscountVM, child) {
          return Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              offersAndDiscountVM.isHistoryLoading
                  ? Container(
                      height: 200.h,
                      decoration: RoundedRectangleBorder().toSmoothCornerDecoration(
                        color: AppColors.whiteColor,
                        borderRadius: 24.h,
                        hasShadow: true,
                      ),
                      child: Center(child: Utils.getLoadingWidget()),
                    ).paddingSymmetrical(24.h, 0.h)
                  : ListView.separated(
                      padding: EdgeInsets.only(top: 12.h),
                      shrinkWrap: true,
                      physics: NeverScrollableScrollPhysics(),
                      itemCount: offersAndDiscountVM.filteredHistory.isNotEmpty ? offersAndDiscountVM.filteredHistory.length : 1,
                      itemBuilder: (context, index) {
                        if (offersAndDiscountVM.filteredHistory.isEmpty) {
                          return Utils.getNoDataWidget(context, noDataText: LocaleKeys.noDataAvailable.tr(context: context));
                        }

                        final offer = offersAndDiscountVM.filteredHistory[index];
                        final status = _getOfferStatus(offer.endDate, offer.isActive);

                        return AnimationConfiguration.staggeredList(
                          position: index,
                          duration: const Duration(milliseconds: 500),
                          child: SlideAnimation(
                            verticalOffset: 100.0,
                            child: FadeInAnimation(
                              child: AnimatedContainer(
                                duration: Duration(milliseconds: 300),
                                curve: Curves.easeInOut,
                                decoration: RoundedRectangleBorder().toSmoothCornerDecoration(
                                  color: AppColors.whiteColor,
                                  borderRadius: 24.h,
                                  hasShadow: true,
                                ),
                                child: Stack(
                                  children: [
                                    Padding(
                                      padding: EdgeInsets.all(16.h),
                                      child: Column(
                                        crossAxisAlignment: CrossAxisAlignment.start,
                                        children: [
                                          // Title with space for status chip
                                          Padding(
                                            padding: EdgeInsets.only(right: 80.w),
                                            child: offer.title?.toText18(
                                                  isBold: true,
                                                  weight: FontWeight.w700,
                                                ) ??
                                                SizedBox(),
                                          ),
                                          SizedBox(height: 12.h),

                                          // Info chips
                                          Wrap(
                                            spacing: 8.w,
                                            runSpacing: 8.h,
                                            children: [
                                              // Start Date chip
                                              if (offer.startDate != null)
                                                AppCustomChipWidget(
                                                  labelText: _formatDateString(offer.startDate),
                                                  backgroundColor: AppColors.chipBgColor,
                                                  textColor: AppColors.textColor,
                                                  icon: AppAssets.calendar,
                                                  iconSize: 12.h,
                                                  iconColor: AppColors.textColor,
                                                  isEnglishOnly: true,
                                                ),
                                              // Hospital/Facility chip
                                              if (offer.facilityType != null)
                                                AppCustomChipWidget(
                                                  labelText: offer.facilityType!,
                                                  backgroundColor: AppColors.chipBgColor,
                                                  textColor: AppColors.textColor,
                                                ),
                                              // Purchase date chip (using startDate as purchased date)
                                              if (offer.startDate != null)
                                                AppCustomChipWidget(
                                                  labelText: "Purchased ${_formatDateString(offer.startDate)}",
                                                  backgroundColor: AppColors.chipBgColor,
                                                  textColor: AppColors.textColor,
                                                  isEnglishOnly: true,
                                                ),
                                              // Valid until chip
                                              if (offer.endDate != null)
                                                AppCustomChipWidget(
                                                  labelText: "Valid till ${_formatDateString(offer.endDate)}",
                                                  backgroundColor: AppColors.chipBgColor,
                                                  textColor: AppColors.textColor,
                                                  icon: AppAssets.calendar,
                                                  iconSize: 12.h,
                                                  iconColor: AppColors.textColor,
                                                  isEnglishOnly: true,
                                                ),
                                              // Order ID chip (using offer.id)
                                              if (offer.id != null)
                                                AppCustomChipWidget(
                                                  labelText: "ID: #${offer.id}",
                                                  backgroundColor: AppColors.chipBgColor,
                                                  textColor: AppColors.textColor,
                                                  isEnglishOnly: true,
                                                ),
                                            ],
                                          ),
                                          SizedBox(height: 16.h),

                                          // Action buttons
                                          Row(
                                            children: [
                                              Expanded(
                                                child: CustomButton(
                                                  text: 'View Offer Details',
                                                  onPressed: () {
                                                    Navigator.of(context).push(
                                                      CustomPageRoute(
                                                        page: OffersAndDiscountsDetailedPage(
                                                          offer: offersAndDiscountVM.filteredOffers[index],
                                                        ),
                                                      ),
                                                    );
                                                  },
                                                  backgroundColor: AppColors.errorColor.withValues(alpha: 0.1),
                                                  borderColor: Colors.transparent,
                                                  textColor: AppColors.errorColor,
                                                  fontSize: 12.f,
                                                  isBold: true,
                                                  borderRadius: 12.r,
                                                  height: 40.h,
                                                ),
                                              ),
                                              SizedBox(width: 12.w),
                                              Expanded(
                                                child: CustomButton(
                                                  text: 'View Order Details',
                                                  onPressed: () {
                                                    // Handle view order details
                                                  },
                                                  backgroundColor: AppColors.whiteColor,
                                                  borderColor: AppColors.textColor,
                                                  textColor: AppColors.textColor,
                                                  fontSize: 12.f,
                                                  isBold: true,
                                                  borderRadius: 12.r,
                                                  height: 40.h,
                                                ),
                                              ),
                                            ],
                                          ),
                                        ],
                                      ),
                                    ),
                                    // Status chip at top right
                                    Positioned(
                                      top: 16.h,
                                      right: 16.w,
                                      child: AppCustomChipWidget(
                                        labelText: status,
                                        backgroundColor: _getStatusBgColor(status),
                                        textColor: _getStatusTextColor(status),
                                      ),
                                    ),
                                  ],
                                ),
                              ).paddingSymmetrical(24.h, 0.h),
                            ),
                          ),
                        );
                      },
                      separatorBuilder: (BuildContext cxt, int index) => SizedBox(height: 16.h),
                    ),
              SizedBox(height: 24.h),
            ],
          );
        }),
      ),
    );
  }
}
