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/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/int_extensions.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/notifications/notifications_view_model.dart';
import 'package:hmg_patient_app_new/features/todo_section/todo_section_view_model.dart';
import 'package:hmg_patient_app_new/generated/locale_keys.g.dart';
import 'package:hmg_patient_app_new/presentation/lab/lab_result_item_view.dart';
import 'package:hmg_patient_app_new/presentation/notifications/notification_details_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:provider/provider.dart';
import 'package:intl/intl.dart';
import 'dart:ui' as ui;

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

  @override
  State<NotificationsListPage> createState() => _NotificationsListPageState();
}

class _NotificationsListPageState extends State<NotificationsListPage> {
  final GlobalKey _bottomKey = GlobalKey();

  void _scrollToBottom() {
    WidgetsBinding.instance.addPostFrameCallback((_) {
      final ctx = _bottomKey.currentContext;
      if (ctx != null) {
        Scrollable.ensureVisible(
          ctx,
          duration: const Duration(milliseconds: 400),
          curve: Curves.easeOut,
        );
      }
    });
  }

  @override
  Widget build(BuildContext context) {
    return CollapsingListView(
      title: LocaleKeys.notification.tr(context: context),
      child: Consumer<NotificationsViewModel>(builder: (context, notificationsVM, child) {
        return Column(
          children: [
            Container(
              margin: EdgeInsets.symmetric(vertical: 24.h),
              decoration: RoundedRectangleBorder().toSmoothCornerDecoration(
                color: AppColors.whiteColor,
                borderRadius: 24.h,
                hasShadow: false,
              ),
              child: ListView.builder(
                  itemCount: notificationsVM.isNotificationsLoading
                      ? 4
                      // : notificationsVM.notificationsList.length + (notificationsVM.hasMoreNotifications ? 1 : 0),
                      : notificationsVM.notificationsList.length,
                  physics: NeverScrollableScrollPhysics(),
                  shrinkWrap: true,
                  padding: EdgeInsetsGeometry.zero,
                  itemBuilder: (context, index) {
                    if (notificationsVM.isNotificationsLoading) {
                      return LabResultItemView(
                        onTap: () {},
                        labOrder: null,
                        index: index,
                        isLoading: true,
                      );
                    }
                    return AnimationConfiguration.staggeredList(
                      position: index,
                      duration: const Duration(milliseconds: 500),
                      child: SlideAnimation(
                        verticalOffset: 100.0,
                        child: FadeInAnimation(
                          child: GestureDetector(
                            onTap: () {
                              notificationsVM.markAsRead(notificationID: notificationsVM.notificationsList[index].id ?? 0);
                              getIt.get<TodoSectionViewModel>().getPatientDashboard();
                              Navigator.push(
                                context,
                                MaterialPageRoute(
                                  builder: (context) => NotificationDetailsPage(
                                    notification: notificationsVM.notificationsList[index],
                                  ),
                                ),
                              );
                            },
                            child: AnimatedContainer(
                              duration: Duration(milliseconds: 300),
                              curve: Curves.easeInOut,
                              child: Column(
                                crossAxisAlignment: CrossAxisAlignment.start,
                                children: [
                                  SizedBox(height: 16.h),
                                  // Message row with red dot for unread
                                  Row(
                                    crossAxisAlignment: CrossAxisAlignment.start,
                                    children: [
                                      Expanded(
                                        child: notificationsVM.notificationsList[index].message!.toText16(
                                          isBold: (notificationsVM.notificationsList[index].isRead == false),
                                          weight: (notificationsVM.notificationsList[index].isRead == false) ? FontWeight.w600 : FontWeight.w400,
                                        ),
                                      ),
                                      SizedBox(width: 8.w),
                                      // Red dot for unread notifications ONLY
                                      if (notificationsVM.notificationsList[index].isRead == false)
                                        Container(
                                          width: 8.w,
                                          height: 8.w,
                                          decoration: BoxDecoration(
                                            color: Colors.red,
                                            shape: BoxShape.circle,
                                          ),
                                        ),
                                    ],
                                  ),
                                  SizedBox(height: 12.h),
                                  // First row: Time and Date chips with arrow
                                  Row(
                                    children: [
                                      // Time chip with clock icon
                                      Container(
                                        padding: EdgeInsets.symmetric(horizontal: 8.w, vertical: 4.h),
                                        decoration: BoxDecoration(
                                          color: AppColors.greyColor,
                                          borderRadius: BorderRadius.circular(8),
                                        ),
                                        child: Directionality(
                                          textDirection: ui.TextDirection.ltr,
                                          child: Row(
                                            mainAxisSize: MainAxisSize.min,
                                            children: [
                                              Icon(Icons.access_time, size: 12.w, color: AppColors.textColor),
                                              SizedBox(width: 4.w),
                                              _formatTime(notificationsVM.notificationsList[index].isSentOn).toText10(weight: FontWeight.w600, color: AppColors.textColor, isEnglishOnly: true),
                                            ],
                                          ),
                                        ),
                                      ),
                                      SizedBox(width: 8.w),
                                      // Date chip with calendar icon
                                      Container(
                                        padding: EdgeInsets.symmetric(horizontal: 8.w, vertical: 4.h),
                                        decoration: BoxDecoration(
                                          color: AppColors.greyColor,
                                          borderRadius: BorderRadius.circular(8),
                                        ),
                                        child: Directionality(
                                          textDirection: ui.TextDirection.ltr,
                                          child: Row(
                                            mainAxisSize: MainAxisSize.min,
                                            children: [
                                              Icon(Icons.calendar_today, size: 12.w, color: AppColors.textColor),
                                              SizedBox(width: 4.w),
                                              _formatDate(notificationsVM.notificationsList[index].isSentOn).toText10(weight: FontWeight.w600, color: AppColors.textColor, isEnglishOnly: true),
                                            ],
                                          ),
                                        ),
                                      ),
                                      Spacer(),
                                      // Arrow icon
                                      Transform.flip(
                                        flipX: getIt.get<AppState>().isArabic(),
                                        child: Utils.buildSvgWithAssets(
                                          icon: AppAssets.arrow_forward,
                                          width: 16.w,
                                          height: 16.h,
                                          iconColor: AppColors.greyTextColor,
                                        ),
                                      ),
                                    ],
                                  ),
                                  // Second row: Contains Image chip (if MessageType is "image")
                                  if (notificationsVM.notificationsList[index].messageType != null && notificationsVM.notificationsList[index].messageType!.toLowerCase() == "image")
                                    Padding(
                                      padding: EdgeInsets.only(top: 8.h),
                                      child: Row(
                                        children: [
                                          Container(
                                            padding: EdgeInsets.symmetric(horizontal: 8.w, vertical: 4.h),
                                            decoration: BoxDecoration(
                                              color: AppColors.greyColor,
                                              borderRadius: BorderRadius.circular(8),
                                            ),
                                            child: Row(
                                              mainAxisSize: MainAxisSize.min,
                                              children: [
                                                Icon(Icons.image_outlined, size: 12.w, color: AppColors.textColor),
                                                SizedBox(width: 4.w),
                                                LocaleKeys.containsImage.toText10(
                                                  weight: FontWeight.w600,
                                                  color: AppColors.textColor,
                                                ),
                                              ],
                                            ),
                                          ),
                                        ],
                                      ),
                                    ),
                                  SizedBox(height: 16.h),
                                  1.divider,
                                ],
                              ),
                            ),
                          ),
                        ),
                      ),
                    );
                  }).paddingSymmetrical(16.w, 0.h),
            ).paddingSymmetrical(24.w, 0.h),
            SizedBox(height: 16.h),
            // SizedBox(
            //   key: _bottomKey,
            //   child: "Show more notifications".toText16(
            //     color: AppColors.primaryRedColor,
            //     isBold: true,
            //     isUnderLine: true
            //   ),
            // ).onPress(() async {
            //   await notificationsVM.loadMoreNotifications();
            //   _scrollToBottom();
            // }),
            SizedBox(height: 24.h),
          ],
        );
      }),
    );
  }

  String _formatTime(String? dateTimeString) {
    if (dateTimeString == null || dateTimeString.isEmpty) return '--';
    try {
      final dateTime = DateUtil.convertStringToDate(dateTimeString);
      return DateFormat('hh:mm a').format(dateTime);
    } catch (e) {
      return '--';
    }
  }

  String _formatDate(String? dateTimeString) {
    if (dateTimeString == null || dateTimeString.isEmpty) return '--';
    try {
      final dateTime = DateUtil.convertStringToDate(dateTimeString);
      return DateFormat('dd MMM yyyy').format(dateTime);
    } catch (e) {
      return '--';
    }
  }
}
