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/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/todo_section/models/resp_models/ancillary_order_list_response_model.dart';
import 'package:hmg_patient_app_new/generated/locale_keys.g.dart';
import 'package:hmg_patient_app_new/theme/colors.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';

class AncillaryProceduresList extends StatelessWidget {
  final List<AncillaryOrderItem> orders;
  final Function(AncillaryOrderItem order)? onCheckIn;
  final Function(AncillaryOrderItem order)? onViewDetails;

  const AncillaryProceduresList({
    super.key,
    required this.orders,
    this.onCheckIn,
    this.onViewDetails,
  });

  @override
  Widget build(BuildContext context) {
    // Show empty state
    if (orders.isEmpty) {
      return _buildDefaultEmptyState(context);
    }

    // Show orders list
    return ListView.builder(
      shrinkWrap: true,
      physics: const NeverScrollableScrollPhysics(),
      itemCount: orders.length,
      itemBuilder: (context, index) {
        final order = orders[index];

        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: AncillaryOrderCard(
                    order: order,
                    isLoading: false,
                    onCheckIn: onCheckIn != null ? () => onCheckIn!(order) : null,
                    onViewDetails: onViewDetails != null ? () => onViewDetails!(order) : null,
                  )),
            ),
          ),
        );
      },
    );
  }

  Widget _buildDefaultEmptyState(BuildContext context) {
    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.youDontHaveAnyAncillaryOrdersYet.tr(context: context),
            isSmallWidget: true,
            width: 62.w,
            height: 62.h,
          ),
        ),
      ),
    );
  }
}

class AncillaryOrderCard extends StatelessWidget {
  const AncillaryOrderCard({
    super.key,
    required this.order,
    this.isLoading = false,
    this.onCheckIn,
    this.onViewDetails,
  });

  final AncillaryOrderItem order;
  final bool isLoading;
  final VoidCallback? onCheckIn;
  final VoidCallback? onViewDetails;

  @override
  Widget build(BuildContext context) {
    return Container(
      margin: EdgeInsets.only(bottom: 12.h),
      decoration: RoundedRectangleBorder().toSmoothCornerDecoration(
        color: AppColors.whiteColor,
        borderRadius: 24.h,
        hasShadow: false,
      ),
      child: Padding(
        padding: EdgeInsets.all(14.h),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            // Header Row with Order Number and Date
            Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: [
                Row(
                  children: [
                    LocaleKeys.orderNumber.tr(context: context).toText14(
                          color: AppColors.textColorLight,
                          weight: FontWeight.w600,
                        ),
                    SizedBox(width: 4.w),
                    (isLoading ? "12345" : "${order.orderNo ?? '-'}").toText16(isBold: true).toShimmer2(isShow: isLoading),
                  ],
                ),
                if (order.orderDate != null || isLoading)
                  (isLoading ? "Jan 15, 2024" : DateFormat('MMM dd, yyyy').format(order.orderDate!))
                      .toText12(color: AppColors.textColorLight)
                      .toShimmer2(isShow: isLoading),
              ],
            ),

            SizedBox(height: 12.h),

            // Doctor and Clinic Info
            Row(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Expanded(
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      // Doctor Name
                      if (order.doctorName != null || isLoading)
                        (isLoading ? "Dr. John Smith" : order.doctorName!)
                            .toString()
                            .toText14(isBold: true, maxlines: 2)
                            .toShimmer2(isShow: isLoading),

                      SizedBox(height: 4.h),

                      // Clinic Name
                      if (order.clinicName != null || isLoading)
                        (isLoading ? "Cardiology Clinic" : order.clinicName!)
                            .toString()
                            .toText12(
                              isBold: true,
                              color: AppColors.greyTextColor,
                              maxLine: 2,
                            )
                            .toShimmer2(isShow: isLoading),
                    ],
                  ),
                ),
              ],
            ),

            SizedBox(height: 12.h),

            // Chips for Appointment Info and Status
            Wrap(
              direction: Axis.horizontal,
              spacing: 3.h,
              runSpacing: 4.h,
              children: [
                // Appointment Date
                if (order.appointmentDate != null || isLoading)
                  AppCustomChipWidget(
                    icon: AppAssets.calendar,
                    labelText:
                        isLoading ? "Date: Jan 20, 2024" : "Date: ${DateFormat('MMM dd, yyyy').format(order.appointmentDate!)}",
                  ).toShimmer2(isShow: isLoading),

                // Appointment Number
                if (order.appointmentNo != null || isLoading)
                  AppCustomChipWidget(
                    labelText: isLoading ? "Appt #: 98765" : "Appt #: ${order.appointmentNo}",
                  ).toShimmer2(isShow: isLoading),

                // Invoice Number
                if (order.invoiceNo != null || isLoading)
                  AppCustomChipWidget(
                    labelText: isLoading ? "Invoice: 45678" : LocaleKeys.invoiceWithNumber.tr(namedArgs: {'invoiceNo': '${order.invoiceNo}'}),
                  ).toShimmer2(isShow: isLoading),

                // Queued Status
                if (order.isQueued == true || isLoading)
                  AppCustomChipWidget(
                    labelText: LocaleKeys.queued.tr(context: context),
                  ).toShimmer2(isShow: isLoading),

                // Check-in Available Status
                if (order.isCheckInAllow == true || isLoading)
                  AppCustomChipWidget(
                    labelText: LocaleKeys.checkInReady.tr(context: context),
                  ).toShimmer2(isShow: isLoading),
              ],
            ),

            SizedBox(height: 12.h),

            // Action Buttons
            Row(
              children: [
                // Check-in Button (if available)
                if (order.isCheckInAllow == true || isLoading)
                  Expanded(
                    child: CustomButton(
                      text: LocaleKeys.checkIn.tr(context: context),
                      onPressed: () {
                        if (isLoading) {
                          return;
                        } else if (onCheckIn != null) {
                          onCheckIn!();
                        }
                      },
                      backgroundColor: AppColors.primaryRedColor,
                      borderColor: AppColors.primaryRedColor,
                      textColor: AppColors.whiteColor,
                      fontSize: 14.f,
                      isBold: true,
                      borderRadius: 10.r,
                      padding: EdgeInsets.fromLTRB(10.h, 0, 10.h, 0),
                      height: 40.h,
                    ).toShimmer2(isShow: isLoading),
                  ),

                if (order.isCheckInAllow == true || isLoading) SizedBox(width: 8.w),

                // View Details Button
                Expanded(
                  child: CustomButton(
                    text: LocaleKeys.viewDetails.tr(context: context),
                    onPressed: () {
                      if (isLoading) {
                        return;
                      } else if (onViewDetails != null) {
                        onViewDetails!();
                      }
                    },
                    backgroundColor: Color(0xffFEE9EA),
                    borderColor: Color(0xffFEE9EA),
                    textColor: Color(0xffED1C2B),
                    fontSize: 14.f,
                    isBold: true,
                    borderRadius: 10.r,
                    padding: EdgeInsets.fromLTRB(10.h, 0, 10.h, 0),
                    height: 40.h,
                    icon: AppAssets.arrow_forward,
                    iconColor: AppColors.primaryRedColor,
                    iconSize: 15.h,
                  ).toShimmer2(isShow: isLoading),
                ),
              ],
            ),
          ],
        ),
      ),
    );
  }
}
