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/utils/date_util.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/refund_request/models/resp_models/refund_request_list_response_model.dart';
import 'package:hmg_patient_app_new/features/refund_request/refund_request_view_model.dart';
import 'package:hmg_patient_app_new/generated/locale_keys.g.dart';
import 'package:hmg_patient_app_new/presentation/refund_request/refund_request_detail_screen.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 RefundHistoryScreen extends StatefulWidget {
  final int refundType;

  const RefundHistoryScreen({super.key, required this.refundType});

  @override
  State<RefundHistoryScreen> createState() => _RefundHistoryScreenState();
}

class _RefundHistoryScreenState extends State<RefundHistoryScreen> {
  @override
  void initState() {
    super.initState();
    final vm = context.read<RefundRequestViewModel>();
    scheduleMicrotask(() async {
      await vm.getRefundInvoices(refundType: widget.refundType);
    });
  }

  // ── Helpers ──────────────────────────────────────────────────────────────

  String _formatDate(String? rawDate) {
    if (rawDate == null || rawDate.isEmpty) return '';
    try {
      final date = DateUtil.convertStringToDate(rawDate);
      return DateFormat('MMM dd, yyyy').format(date);
    } catch (_) {
      return rawDate;
    }
  }

  // ── Shimmer ───────────────────────────────────────────────────────────────

  Widget _buildLoadingShimmer() {
    return ListView.separated(
      shrinkWrap: true,
      physics: const NeverScrollableScrollPhysics(),
      padding: EdgeInsets.only(top: 24.h),
      itemCount: 4,
      separatorBuilder: (_, __) => SizedBox(height: 16.h),
      itemBuilder: (_, __) => _buildInvoiceCard(null, isLoading: true),
    );
  }

  // ── Card ──────────────────────────────────────────────────────────────────

  Color getStatusColor(int status) {
    Color statusColor = AppColors.textColor;
    if (status == 3) {
      statusColor = AppColors.statusRejectedColor;
    } else if (status == 2) {
      statusColor = AppColors.statusCompletedColor;
    } else if (status == 1) {
      statusColor = AppColors.statusPendingColor;
    }
    return statusColor;
  }

  String getRefundDestinationIcon(String refundDestination) {
    String icon = "";

    if (refundDestination.toLowerCase().contains("wallet")) {
      icon = AppAssets.habibLogoOnly;
    } else if (refundDestination.toLowerCase().contains("bank")) {
      icon = AppAssets.bankIconOnly;
    }

    return icon;
  }

  Widget _buildInvoiceCard(RefundInvoiceModel? invoice, {bool isLoading = false}) {
    final referenceNo = isLoading ? 'INV-000000' : (invoice?.referenceNumber ?? '-');
    final String requestStatusName = isLoading ? 'Processed' : (invoice?.requestStatusName ?? '');
    final int requestStatusId = isLoading ? 1 : (invoice?.requestStatusId ?? 1);
    final refundDestinationId = (invoice?.refundDestination ?? '');
    final refundDestination = isLoading ? 'Wallet' : (invoice?.refundDestination ?? '');
    final isInvoiceRefund = invoice?.refundTypeId == 1;

    // Resolve total refund amount from whichever payload is present
    final totalAmount = isLoading
        ? 0.0
        : isInvoiceRefund
            ? (invoice?.invoiceRequestPayload?.totalRefundAmount)
            : (invoice?.walletRequestPayload?.totalRefundAmount);
    final totalAmountStr = totalAmount?.toStringAsFixed(2);

    // Resolve total refund amount from whichever payload is present
    final projectName = isInvoiceRefund ? (invoice?.invoiceRequestPayload?.project ?? "") : "";
    final String totalProcedures = (invoice?.invoiceRequestPayload?.proceduresList?.length.toString() ?? '');

    return AnimatedContainer(
      duration: const Duration(milliseconds: 300),
      curve: Curves.easeInOut,
      decoration: RoundedRectangleBorder().toSmoothCornerDecoration(
        color: AppColors.whiteColor,
        borderRadius: 24.r,
        hasShadow: false,
      ),
      child: Padding(
        padding: EdgeInsets.all(16.w),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            // Invoice No + Last Updated row

            AppCustomChipWidget(
              icon: "",
              labelText: requestStatusName,
              textColor: getStatusColor(requestStatusId),
              backgroundColor: getStatusColor(requestStatusId).withValues(alpha: 0.2),
            ).toShimmer2(isShow: isLoading),
            SizedBox(height: 8.h),

            Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: [
                "${LocaleKeys.referenceNo.tr(context: context)}  $referenceNo"
                    .toText16(
                      color: AppColors.textColor,
                      isBold: true,
                    )
                    .toShimmer2(isShow: isLoading),
              ],
            ),

            SizedBox(height: 8.h),
            Wrap(
              spacing: 6.w,
              runSpacing: 6.h,
              children: [
                if (!isLoading && refundDestination.isNotEmpty)
                  AppCustomChipWidget(icon: getRefundDestinationIcon(refundDestination), iconHasColor: false, labelText: refundDestination),
                if (totalProcedures.isNotEmpty) AppCustomChipWidget(icon: "", labelText: "$totalProcedures ${LocaleKeys.procedures.tr()}"),
                if (!isLoading && projectName.isNotEmpty) AppCustomChipWidget(icon: "", labelText: projectName),
              ],
            ),

            SizedBox(height: 16.h),

            // Total refund amount
            if (totalAmountStr != null)
              Utils.getPaymentAmountWithSymbol(
                isExpanded: false,
                (isLoading ? '0.00' : totalAmountStr).toText20(isBold: true, color: AppColors.textColor),
                AppColors.textColor,
                18,
                isSaudiCurrency: true,
              ).toShimmer2(isShow: isLoading),

            SizedBox(height: 16.h),
            CustomButton(
              text: LocaleKeys.viewDetails.tr(context: context),
              onPressed: () => Navigator.of(context).push(CustomPageRoute(page: RefundRequestDetailScreen(invoice: invoice!))),
              backgroundColor: AppColors.primaryRedColor.withValues(alpha: 0.1),
              borderColor: AppColors.primaryRedColor.withValues(alpha: 0.01),
              textColor: AppColors.primaryRedColor,
              fontSize: 14.f,
              fontWeight: FontWeight.w600,
              borderRadius: 12.r,
              padding: EdgeInsets.symmetric(horizontal: 10.w),
              height: 40.h,
              iconColor: AppColors.whiteColor,
              iconSize: 18.h,
            ).toShimmer2(isShow: isLoading),
          ],
        ),
      ),
    );
  }

  // ── Empty ─────────────────────────────────────────────────────────────────

  Widget _buildEmptyState() {
    return Center(
      child: Padding(
        padding: EdgeInsets.symmetric(vertical: 40.h),
        child: Container(
          decoration: RoundedRectangleBorder().toSmoothCornerDecoration(
            color: AppColors.whiteColor,
            borderRadius: 12.r,
            hasShadow: false,
          ),
          child: Utils.getNoDataWidget(
            context,
            noDataText: LocaleKeys.noRefundHistoryFound.tr(context: context),
            isSmallWidget: true,
            width: 62.w,
            height: 62.h,
          ),
        ),
      ),
    );
  }

  // ── Build ─────────────────────────────────────────────────────────────────

  @override
  Widget build(BuildContext context) {
    return CollapsingListView(
      title: LocaleKeys.refundHistory.tr(context: context),
      isLeading: true,
      child: SingleChildScrollView(
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Consumer<RefundRequestViewModel>(
              builder: (context, viewModel, _) {
                if (viewModel.isRefundInvoicesLoading) {
                  return _buildLoadingShimmer();
                }

                if (viewModel.refundInvoicesList.isEmpty) {
                  return _buildEmptyState();
                }
                return ListView.separated(
                  padding: EdgeInsets.only(top: 24.h),
                  shrinkWrap: true,
                  physics: const NeverScrollableScrollPhysics(),
                  itemCount: viewModel.refundInvoicesList.length,
                  separatorBuilder: (_, __) => SizedBox(height: 12.h),
                  itemBuilder: (context, index) {
                    final invoice = viewModel.refundInvoicesList[index];
                    return AnimationConfiguration.staggeredList(
                      position: index,
                      duration: const Duration(milliseconds: 500),
                      child: SlideAnimation(
                        verticalOffset: 100.0,
                        child: FadeInAnimation(
                          child: _buildInvoiceCard(invoice),
                        ),
                      ),
                    );
                  },
                );
              },
            ),
          ],
        ).paddingSymmetrical(24.w, 0),
      ),
    );
  }
}
