import 'dart:async';

import 'package:easy_localization/easy_localization.dart';
import 'package:flutter/material.dart';
import 'package:hmg_patient_app_new/core/app_assets.dart';
import 'package:hmg_patient_app_new/core/app_export.dart';
import 'package:hmg_patient_app_new/core/dependencies.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/lab/models/Range.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';
import 'package:hmg_patient_app_new/widgets/custom_tab_bar.dart';
import 'package:hmg_patient_app_new/widgets/date_range_selector/models/calendar_design_type.dart';
import 'package:hmg_patient_app_new/widgets/date_range_selector/viewmodel/date_range_calendar_model.dart';
import 'package:hmg_patient_app_new/widgets/date_range_selector/viewmodel/date_range_view_model.dart' show DateRangeSelectorRangeViewModel;
import 'package:provider/provider.dart';
import 'package:syncfusion_flutter_datepicker/datepicker.dart';

typedef OnRangeSelected = void Function(DateTime? start, DateTime? end);
typedef OnCalendarTypeChanged = void Function(bool isGregorian);

class DateRangeSelector extends StatefulWidget {
  final OnRangeSelected onRangeSelected;
  final CalendarDesignType designType;
  final bool showCalendarToggle;
  final OnCalendarTypeChanged? onCalendarTypeChanged;
  final String? btnTitle;

  const DateRangeSelector({
    super.key,
    required this.onRangeSelected,
    this.designType = CalendarDesignType.defaultUI,
    this.showCalendarToggle = true,
    this.onCalendarTypeChanged,
    this.btnTitle,
  });

  @override
  State<DateRangeSelector> createState() => _DateRangeSelectorState();
}

enum PickerViewMode {
  date,
  month,
  year,
}

class _DateRangeSelectorState extends State<DateRangeSelector> {
  late DateRangePickerController _calendarController;
  DateTime? start;
  DateTime? end;
  late DateRangeSelectorRangeViewModel model;
  PickerViewMode _viewMode = PickerViewMode.date;

  // Prevent Syncfusion's initial onViewChanged callback from scheduling an
  // unnecessary second build of the same month.
  late int _displayedMonthKey;

  // Track the current Hijri month/year being displayed (for header display accuracy)
  HijriGregDate? _currentHijriDisplay;

  @override
  void initState() {
    _calendarController = DateRangePickerController();
    final today = DateTime.now();
    _displayedMonthKey = _monthKey(today);
    if (widget.designType == CalendarDesignType.designV2) {
      _calendarController.displayDate = today;
    }
    scheduleMicrotask(() {
      if (widget.designType == CalendarDesignType.designV2) {
        // For V2, select today's date by default
        _calendarController.selectedDate = today;
        model.updateSelectedDate(today);
      } else {
        // For default UI, use range selection
        _calendarController.selectedRange = PickerDateRange(model.fromDate, model.toDate);
      }
    });
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    model = Provider.of<DateRangeSelectorRangeViewModel>(context);

    if (widget.designType != CalendarDesignType.designV2) {
      _calendarController.selectedRange = PickerDateRange(model.fromDate, model.toDate);
    }

    return widget.designType == CalendarDesignType.designV2 ? _buildDesignV2(widget.btnTitle) : _buildDefaultUI();
  }

  Widget _buildDefaultUI() {
    return Padding(
      padding: EdgeInsets.symmetric(horizontal: 0.h),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Consumer<DateRangeSelectorRangeViewModel>(
            builder: (_, model, __) => selectionChip(model),
          ).paddingOnly(bottom: 16.h),
          Container(
            decoration: RoundedRectangleBorder().toSmoothCornerDecoration(color: AppColors.whiteColor, borderRadius: 20.h, hasShadow: false),
            padding: EdgeInsets.all(16.h),
            child: Column(
              children: [
                Row(
                  children: [
                    fromDateComponent(),
                    Text(
                      LocaleKeys.to.tr(context: context),
                      style: TextStyle(color: AppColors.calenderTextColor, fontSize: 14.f, fontWeight: FontWeight.w600, letterSpacing: -.2),
                    ).paddingSymmetrical(24.h, 0.h),
                    toDateComponent(),
                  ],
                ),
                Divider(
                  color: AppColors.spacerLineColor,
                  thickness: 1,
                ).paddingOnly(bottom: 16.h, top: 16.h),
                Material(
                  color: AppColors.whiteColor,
                  child: SfDateRangePicker(
                    controller: _calendarController,
                    selectionMode: DateRangePickerSelectionMode.range,
                    showNavigationArrow: true,
                    headerHeight: 40.h,
                    backgroundColor: AppColors.whiteColor,
                    headerStyle: DateRangePickerHeaderStyle(
                      backgroundColor: AppColors.whiteColor,
                      textAlign: TextAlign.start,
                      textStyle: TextStyle(
                        fontSize: 18.f,
                        fontWeight: FontWeight.w600,
                        letterSpacing: -0.46,
                        color: AppColors.primaryRedColor,
                        fontFamily: "Poppins",
                      ),
                    ),
                    monthViewSettings: DateRangePickerMonthViewSettings(
                      viewHeaderStyle: DateRangePickerViewHeaderStyle(
                        backgroundColor: AppColors.whiteColor,
                        textStyle: TextStyle(
                          fontSize: 12.f,
                          fontWeight: FontWeight.w600,
                          letterSpacing: -0.46,
                          color: AppColors.textColor,
                        ),
                      ),
                      showTrailingAndLeadingDates: false,
                      dayFormat: "EEE",
                    ),
                    selectionShape: DateRangePickerSelectionShape.rectangle,
                    selectionRadius: 12.h,
                    selectionColor: AppColors.transparent,
                    selectionTextStyle: TextStyle(
                      fontFamily: "Poppins",
                    ),
                    startRangeSelectionColor: AppColors.primaryRedColor,
                    endRangeSelectionColor: AppColors.primaryRedColor,
                    rangeSelectionColor: AppColors.primaryRedColor.withOpacity(0.1),
                    rangeTextStyle: TextStyle(
                      fontFamily: "Poppins",
                    ),
                    todayHighlightColor: Colors.transparent,
                    monthCellStyle: DateRangePickerMonthCellStyle(
                      textStyle: TextStyle(
                        fontFamily: "Poppins",
                        fontSize: 12.f,
                        color: AppColors.textColor,
                      ),
                      todayTextStyle: TextStyle(
                        fontFamily: "Poppins",
                        color: AppColors.textColor,
                        fontWeight: FontWeight.bold,
                      ),
                    ),
                    onSelectionChanged: (DateRangePickerSelectionChangedArgs args) {
                      print("the value is ${args.value}");
                      if (args.value is PickerDateRange) {
                        final PickerDateRange range = args.value;
                        start = range.startDate;
                        end = range.endDate;
                        model.fromDate = start;
                        model.toDate = end;
                        if (end == null) {
                          scheduleMicrotask(() {
                            model.resetCurrentlySelectedRange();
                          });
                        }
                      }
                    },
                  ),
                ),
              ],
            ),
          ),
          Row(
            children: [
              Consumer<DateRangeSelectorRangeViewModel>(
                builder: (_, model, __) => Visibility(
                  visible: (model.fromDate != null || model.toDate != null),
                  child: Expanded(
                    child: Row(
                      children: [
                        Expanded(
                          child: CustomButton(
                            text: LocaleKeys.cancel.tr(context: context),
                            onPressed: () {
                              _calendarController.selectedRange = null;
                              _calendarController.selectedDate = null;
                              model.flush();
                              Navigator.of(context).pop();
                              widget.onRangeSelected(null, null);
                            },
                            backgroundColor: AppColors.secondaryLightRedColor,
                            borderColor: AppColors.secondaryLightRedColor,
                            textColor: AppColors.primaryRedColor,
                            icon: AppAssets.cancel,
                            iconColor: AppColors.primaryRedColor,
                            height: 56.h,
                          ),
                        ),
                        SizedBox(
                          width: 16.h,
                        )
                      ],
                    ),
                  ),
                ),
              ),
              Expanded(
                child: CustomButton(
                  text: LocaleKeys.search.tr(context: context),
                  onPressed: () {
                    Navigator.of(context).pop();
                    widget.onRangeSelected(model.fromDate, model.toDate);
                  },
                  backgroundColor: AppColors.lightGreenButtonColor,
                  borderColor: Colors.transparent,
                  textColor: AppColors.textGreenColor,
                  icon: AppAssets.reminder_bell,
                  iconColor: AppColors.textGreenColor,
                  height: 56.h,
                ),
              ),
            ],
          ).paddingOnly(top: 24.h),
        ],
      ),
    );
  }

  Widget _buildDesignV2(String? btnTitle) {
    return ChangeNotifierProvider(
      create: (_) => DateRangCalenderModel(appState: getIt(), navigationService: getIt(), dialogService: getIt()),
      child: Consumer<DateRangCalenderModel>(
        builder: (context, calendarModel, child) {
          // Check if current language is Arabic
          final bool isArabic = context.locale.languageCode == 'ar';

          return Padding(
            padding: EdgeInsets.symmetric(horizontal: 0.h),
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                // Conditionally show calendar toggle
                if (widget.showCalendarToggle)
                  Selector<DateRangCalenderModel, int>(
                    selector: (_, model) => model.getSelectedTabIndex,
                    builder: (context, selectedIndex, child) => CustomTabBar(
                      activeBackgroundColor: AppColors.secondaryLightRedColor,
                      activeTextColor: AppColors.primaryRedColor,
                      initialIndex: selectedIndex,
                      tabs: [CustomTabBarModel(null, LocaleKeys.gregorianDate.tr()), CustomTabBarModel(null, LocaleKeys.hijriDate.tr())],
                      onTabChange: (index) {
                        final calendarModel = Provider.of<DateRangCalenderModel>(context, listen: false);
                        if (calendarModel.getSelectedTabIndex == index) return;

                        // Update local fields before notifying the provider so
                        // the calendar changes with a single rebuild.
                        _viewMode = PickerViewMode.date;
                        _currentHijriDisplay = null;
                        calendarModel.setTabIndex(index);

                        // Notify parent widget about calendar type change (e.g., AuthenticationViewModel)
                        final isGregorian = index == 0;
                        widget.onCalendarTypeChanged?.call(isGregorian);
                      },
                    ),
                  ),
                if (widget.showCalendarToggle)
                  SizedBox(
                    height: 16.w,
                  ),

                Container(
                  decoration: RoundedRectangleBorder().toSmoothCornerDecoration(color: AppColors.whiteColor, borderRadius: 20.h, hasShadow: false),
                  padding: EdgeInsets.all(16.h),
                  child: Column(
                    children: [
                      // Show custom header for both calendar types
                      _buildCalendarHeader(isArabic, calendarModel),
                      // Wrap all views in SizedBox for consistent height
                      SizedBox(
                        height: 272.h, // Fixed height for calendar body only (no header)
                        child: Material(
                          color: AppColors.whiteColor,
                          // Rebuild when view mode or calendar type changes
                          // Syncfusion caches its rendered date cells. Include
                          // the calendar type in the key so Gregorian/Hijri day
                          // labels refresh immediately when the tab changes.
                          // Hijri conversion is now constant-time, so this
                          // targeted recreation remains responsive.
                          key: ValueKey('${calendarModel.getSelectedTabIndex}-$_viewMode'),
                          child: _viewMode == PickerViewMode.month
                              ? _buildMonthPicker(isArabic, calendarModel)
                              : _viewMode == PickerViewMode.year
                              ? _buildYearPicker(isArabic, calendarModel)
                              : (calendarModel.isHijri ? _buildHijriCalendar(isArabic) : _buildGregorianCalendar(isArabic)),
                        ),
                      ),
                    ],
                  ),
                ),
                // Only Select button for V2 (no cancel button)
                CustomButton(
                  text: btnTitle ?? LocaleKeys.select.tr(context: context),
                  onPressed: () {
                    // Don't reset calendar type - keep user's preference
                    Navigator.of(context).pop();
                    // For single date selection, pass the same date as both start and end
                    widget.onRangeSelected(model.fromDate, model.fromDate);
                  },
                  backgroundColor: AppColors.primaryRedColor,
                  borderColor: Colors.transparent,
                  textColor: AppColors.whiteColor,
                  height: 56.h,
                ).paddingOnly(top: 24.h),
                // Bottom image from ui2.png
                SizedBox(height: 16.h),
              ],
            ),
          );
        },
      ),
    );
  }

  // Build Gregorian calendar (Design V2 - Single Date Selection)
  Widget _buildGregorianCalendar(bool isArabic) {
    final today = DateTime.now();

    return SfDateRangePicker(
      controller: _calendarController,
      selectionMode: DateRangePickerSelectionMode.single,
      showNavigationArrow: false,
      headerHeight: 0,
      // Hide built-in header, use custom header
      backgroundColor: AppColors.whiteColor,
      monthViewSettings: DateRangePickerMonthViewSettings(
        viewHeaderStyle: DateRangePickerViewHeaderStyle(
          backgroundColor: AppColors.whiteColor,
          textStyle: TextStyle(
            fontSize: 12.f,
            fontWeight: FontWeight.w600,
            letterSpacing: -0.46,
            color: AppColors.textColor,
          ),
        ),
        showTrailingAndLeadingDates: false,
        dayFormat: "EEE",
      ),
      // Custom cell builder for square border selection
      cellBuilder: (BuildContext context, DateRangePickerCellDetails cellDetails) {
        if (cellDetails.date != DateTime(0)) {
          final isToday = cellDetails.date.day == today.day && cellDetails.date.month == today.month && cellDetails.date.year == today.year;
          final isSelected = _calendarController.selectedDate != null &&
              cellDetails.date.day == _calendarController.selectedDate!.day &&
              cellDetails.date.month == _calendarController.selectedDate!.month &&
              cellDetails.date.year == _calendarController.selectedDate!.year;

          return Container(
            alignment: Alignment.center,
            decoration: BoxDecoration(
              borderRadius: BorderRadius.circular(8.h),
              border: isSelected ? Border.all(color: AppColors.primaryRedColor, width: 2) : null,
              color: Colors.transparent,
            ),
            child: Text(
              cellDetails.date.day.toString(),
              style: TextStyle(
                fontFamily: "Poppins",
                fontSize: 12.f,
                color: AppColors.textColor,
                fontWeight: isToday ? FontWeight.bold : (isSelected ? FontWeight.w600 : FontWeight.normal),
              ),
            ),
          );
        }
        return Container();
      },
      selectionShape: DateRangePickerSelectionShape.rectangle,
      selectionRadius: 8.h,
      selectionColor: Colors.transparent,
      selectionTextStyle: TextStyle(
        fontFamily: "Poppins",
        color: AppColors.textColor,
        fontWeight: FontWeight.w600,
      ),
      todayHighlightColor: Colors.transparent,
      monthCellStyle: DateRangePickerMonthCellStyle(
        textStyle: TextStyle(
          fontFamily: "Poppins",
          fontSize: 12.f,
          color: AppColors.textColor,
        ),
        todayTextStyle: TextStyle(
          fontFamily: "Poppins",
          color: AppColors.textColor,
          fontWeight: FontWeight.bold,
        ),
      ),
      onViewChanged: (DateRangePickerViewChangedArgs args) {
        _handleCalendarViewChanged(args);
      },
      onSelectionChanged: (DateRangePickerSelectionChangedArgs args) {
        if (args.value is DateTime) {
          setState(() {
            start = args.value;
            end = args.value;
          });
          model.updateSelectedDate(args.value);
        }
      },
    );
  }

  // Build one complete Hijri month instead of relabelling the dates in a
  // Gregorian month. A Gregorian month overlaps two Hijri months, which would
  // otherwise produce sequences such as 16...30, 1...17 in the same grid.
  Widget _buildHijriCalendar(bool isArabic) {
    final calendarModel = Provider.of<DateRangCalenderModel>(context, listen: false);
    final today = DateTime.now();
    final displayedGregorian = _calendarController.displayDate ?? today;
    final displayedHijri = _currentHijriDisplay ?? calendarModel.gregorianToHijri(displayedGregorian);
    final firstHijriDay = HijriGregDate(day: 1, month: displayedHijri.month, year: displayedHijri.year);
    final firstGregorianDay = calendarModel.hijriToGregorian(firstHijriDay);
    final leadingEmptyCells = firstGregorianDay.weekday % DateTime.daysPerWeek;
    final daysInMonth = calendarModel.getDaysInMonth(displayedHijri.year, displayedHijri.month);
    final selectedDate = _calendarController.selectedDate;
    const weekdays = [
      DateTime.sunday,
      DateTime.monday,
      DateTime.tuesday,
      DateTime.wednesday,
      DateTime.thursday,
      DateTime.friday,
      DateTime.saturday,
    ];

    return Column(
      children: [
        SizedBox(
          height: 32.h,
          child: Row(
            children: weekdays
                .map(
                  (weekday) => Expanded(
                child: Center(
                  child: Text(
                    calendarModel.getWeekdayNameLocalized(weekday, isArabic),
                    style: TextStyle(
                      fontSize: 12.f,
                      fontWeight: FontWeight.w600,
                      letterSpacing: -0.46,
                      color: AppColors.textColor,
                    ),
                  ),
                ),
              ),
            )
                .toList(),
          ),
        ),
        Expanded(
          child: GridView.builder(
            padding: EdgeInsets.zero,
            physics: const NeverScrollableScrollPhysics(),
            gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
              crossAxisCount: DateTime.daysPerWeek,
              mainAxisExtent: 36.h,
              mainAxisSpacing: 4.h,
            ),
            itemCount: 42,
            itemBuilder: (context, index) {
              final hijriDay = index - leadingEmptyCells + 1;
              if (hijriDay < 1 || hijriDay > daysInMonth) {
                return const SizedBox.shrink();
              }

              final hijriDate = HijriGregDate(day: hijriDay, month: displayedHijri.month, year: displayedHijri.year);
              final gregorianDate = calendarModel.hijriToGregorian(hijriDate);
              final isToday = _isSameDate(gregorianDate, today);
              final isSelected = selectedDate != null && _isSameDate(gregorianDate, selectedDate);

              return GestureDetector(
                behavior: HitTestBehavior.opaque,
                onTap: () {
                  _calendarController.selectedDate = gregorianDate;
                  setState(() {
                    start = gregorianDate;
                    end = gregorianDate;
                  });
                  model.updateSelectedDate(gregorianDate);
                },
                child: Container(
                  alignment: Alignment.center,
                  decoration: BoxDecoration(
                    borderRadius: BorderRadius.circular(8.h),
                    border: isSelected ? Border.all(color: AppColors.primaryRedColor, width: 2) : null,
                    color: Colors.transparent,
                  ),
                  child: Text(
                    hijriDay.toString(),
                    style: TextStyle(
                      fontFamily: "Poppins",
                      fontSize: 12.f,
                      color: AppColors.textColor,
                      fontWeight: isToday ? FontWeight.bold : (isSelected ? FontWeight.w600 : FontWeight.normal),
                    ),
                  ),
                ),
              );
            },
          ),
        ),
      ],
    );
  }

  bool _isSameDate(DateTime first, DateTime second) {
    return first.year == second.year && first.month == second.month && first.day == second.day;
  }

  int _monthKey(DateTime date) => (date.year * 100) + date.month;

  void _changeHijriMonth(DateRangCalenderModel calendarModel, int monthDelta) {
    final displayedDate = _calendarController.displayDate ?? DateTime.now();
    final currentHijri = _currentHijriDisplay ?? calendarModel.gregorianToHijri(displayedDate);
    final zeroBasedMonth = (currentHijri.year * 12) + currentHijri.month - 1 + monthDelta;
    final nextHijriDate = HijriGregDate(
      day: 1,
      month: (zeroBasedMonth % 12) + 1,
      year: zeroBasedMonth ~/ 12,
    );
    final nextGregorianDate = calendarModel.hijriToGregorian(nextHijriDate);

    setState(() {
      _currentHijriDisplay = nextHijriDate;
      _calendarController.displayDate = nextGregorianDate;
      _displayedMonthKey = _monthKey(nextGregorianDate);
    });
  }

  void _handleCalendarViewChanged(DateRangePickerViewChangedArgs args) {
    final rangeStart = args.visibleDateRange.startDate;
    final rangeEnd = args.visibleDateRange.endDate;
    final displayedDate = _calendarController.displayDate ??
        (rangeEnd == null
            ? rangeStart
            : rangeStart?.add(Duration(days: rangeEnd.difference(rangeStart).inDays ~/ 2)));

    if (displayedDate == null) return;

    final newMonthKey = _monthKey(displayedDate);
    if (newMonthKey == _displayedMonthKey) return;

    _displayedMonthKey = newMonthKey;
    _currentHijriDisplay = null;
    WidgetsBinding.instance.addPostFrameCallback((_) {
      if (mounted) {
        setState(() {});
      }
    });
  }

  // Build unified calendar header for both Gregorian and Hijri
  Widget _buildCalendarHeader(bool isArabic, DateRangCalenderModel calendarModel) {
    final displayedDate = _calendarController.displayDate ?? DateTime.now();

    String monthText;
    String yearText;

    if (calendarModel.isHijri) {
      // Use tracked Hijri display date if available, otherwise convert from displayed Gregorian date
      final hijriDate = _currentHijriDisplay ?? calendarModel.gregorianToHijri(displayedDate);
      final monthName = calendarModel.getMonthNameLocalized(hijriDate.month, isArabic);
      monthText = monthName;
      yearText = hijriDate.year.toString();
    } else {
      final monthNames = isArabic
          ? ['يناير', 'فبراير', 'مارس', 'أبريل', 'مايو', 'يونيو', 'يوليو', 'أغسطس', 'سبتمبر', 'أكتوبر', 'نوفمبر', 'ديسمبر']
          : ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'];
      monthText = monthNames[displayedDate.month - 1];
      yearText = displayedDate.year.toString();
    }

    return Padding(
      padding: EdgeInsets.only(bottom: 8.h),
      child: SizedBox(
        height: 40.h,
        child: Row(
          mainAxisAlignment: MainAxisAlignment.spaceBetween,
          children: [
            Row(
              children: [
                // Month text - clickable
                GestureDetector(
                  onTap: () {
                    setState(() {
                      _viewMode = _viewMode == PickerViewMode.month ? PickerViewMode.date : PickerViewMode.month;
                    });
                  },
                  child: Text(
                    monthText,
                    style: TextStyle(
                      fontSize: 18.f,
                      fontWeight: FontWeight.w600,
                      letterSpacing: -0.46,
                      color: AppColors.primaryRedColor,
                      fontFamily: "Poppins",
                    ),
                    textAlign: isArabic ? TextAlign.right : TextAlign.left,
                  ),
                ),
                SizedBox(width: 8.h),
                // Year text - clickable
                GestureDetector(
                  onTap: () {
                    setState(() {
                      _viewMode = _viewMode == PickerViewMode.year ? PickerViewMode.date : PickerViewMode.year;
                    });
                  },
                  child: Text(
                    yearText,
                    style: TextStyle(
                      fontSize: 18.f,
                      fontWeight: FontWeight.w600,
                      letterSpacing: -0.46,
                      color: AppColors.primaryRedColor,
                      fontFamily: "Poppins",
                    ),
                    textAlign: isArabic ? TextAlign.right : TextAlign.left,
                  ),
                ),
              ],
            ),
            Row(
              children: [
                IconButton(
                  icon: Icon(Icons.chevron_left, color: AppColors.primaryRedColor),
                  onPressed: () {
                    if (_viewMode == PickerViewMode.date) {
                      if (calendarModel.isHijri) {
                        _changeHijriMonth(calendarModel, -1);
                      } else {
                        _calendarController.backward!();
                      }
                    } else if (_viewMode == PickerViewMode.year) {
                      // Navigate years backward by 12
                      final currentDate = _calendarController.displayDate ?? DateTime.now();
                      if (calendarModel.isHijri) {
                        // For Hijri, convert back and forth
                        final hijriDate = _currentHijriDisplay ?? calendarModel.gregorianToHijri(currentDate);
                        try {
                          final newHijriDate = HijriGregDate(day: 1, month: hijriDate.month, year: hijriDate.year - 12);
                          final newGregorianDate = calendarModel.hijriToGregorian(newHijriDate);
                          _calendarController.displayDate = newGregorianDate;
                          _currentHijriDisplay = newHijriDate;
                        } catch (e) {
                          // Fallback
                          _calendarController.displayDate = DateTime(currentDate.year - 10, currentDate.month, 1);
                        }
                      } else {
                        _calendarController.displayDate = DateTime(currentDate.year - 12, currentDate.month, 1);
                      }
                      setState(() {});
                    }
                  },
                  padding: EdgeInsets.zero,
                  constraints: BoxConstraints(),
                ),
                SizedBox(width: 8.h),
                IconButton(
                  icon: Icon(Icons.chevron_right, color: AppColors.primaryRedColor),
                  onPressed: () {
                    if (_viewMode == PickerViewMode.date) {
                      if (calendarModel.isHijri) {
                        _changeHijriMonth(calendarModel, 1);
                      } else {
                        _calendarController.forward!();
                      }
                    } else if (_viewMode == PickerViewMode.year) {
                      // Navigate years forward by 12
                      final currentDate = _calendarController.displayDate ?? DateTime.now();
                      if (calendarModel.isHijri) {
                        // For Hijri, convert back and forth
                        final hijriDate = _currentHijriDisplay ?? calendarModel.gregorianToHijri(currentDate);
                        try {
                          final newHijriDate = HijriGregDate(day: 1, month: hijriDate.month, year: hijriDate.year + 12);
                          final newGregorianDate = calendarModel.hijriToGregorian(newHijriDate);
                          _calendarController.displayDate = newGregorianDate;
                          _currentHijriDisplay = newHijriDate;
                        } catch (e) {
                          // Fallback
                          _calendarController.displayDate = DateTime(currentDate.year + 10, currentDate.month, 1);
                        }
                      } else {
                        _calendarController.displayDate = DateTime(currentDate.year + 12, currentDate.month, 1);
                      }
                      setState(() {});
                    }
                  },
                  padding: EdgeInsets.zero,
                  constraints: BoxConstraints(),
                ),
              ],
            ),
          ],
        ),
      ),
    );
  }

  // Build month picker grid
  Widget _buildMonthPicker(bool isArabic, DateRangCalenderModel calendarModel) {
    final displayedDate = _calendarController.displayDate ?? DateTime.now();
    final currentDate = DateTime.now();

    int currentMonth;
    int currentYear;
    int displayedYear;

    if (calendarModel.isHijri) {
      // For Hijri calendar
      final hijriCurrent = calendarModel.gregorianToHijri(currentDate);
      final hijriDisplayed = _currentHijriDisplay ?? calendarModel.gregorianToHijri(displayedDate);
      currentMonth = hijriCurrent.month;
      currentYear = hijriCurrent.year;
      displayedYear = hijriDisplayed.year;
    } else {
      // For Gregorian calendar
      currentMonth = currentDate.month;
      currentYear = currentDate.year;
      displayedYear = displayedDate.year;
    }

    List<String> monthNames;
    if (calendarModel.isHijri) {
      monthNames = isArabic ? DateRangCalenderModel.hijriMonthNamesArabic : DateRangCalenderModel.hijriMonthNamesEnglish;
    } else {
      monthNames = isArabic ? DateRangCalenderModel.gregorianMonthNamesArabic : DateRangCalenderModel.gregorianMonthNamesEnglish;
    }

    return GridView.builder(
      padding: EdgeInsets.all(8.h),
      gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(crossAxisCount: 3, childAspectRatio: 2.5, crossAxisSpacing: 8.h, mainAxisSpacing: 8.h),
      itemCount: 12,
      itemBuilder: (context, index) {
        final monthIndex = index + 1;
        final isCurrentMonth = currentMonth == monthIndex && currentYear == displayedYear;

        return GestureDetector(
          onTap: () {
            // Update the displayed month based on calendar type
            if (calendarModel.isHijri) {
              // Convert Hijri month to Gregorian date
              try {
                final hijriDate = HijriGregDate(day: 1, month: monthIndex, year: displayedYear);
                final gregorianDate = calendarModel.hijriToGregorian(hijriDate);
                _calendarController.displayDate = gregorianDate;
                // Track the Hijri month/year for accurate header display
                _currentHijriDisplay = hijriDate;
              } catch (e) {
                // Fallback if conversion fails
                _calendarController.displayDate = DateTime(displayedDate.year, monthIndex, 1);
              }
            } else {
              // Gregorian month - direct update
              _calendarController.displayDate = DateTime(displayedYear, monthIndex, 1);
            }

            // Switch back to date view
            setState(() {
              _viewMode = PickerViewMode.date;
            });
          },
          child: Container(
            decoration: BoxDecoration(
              borderRadius: BorderRadius.circular(8.h),
              border: isCurrentMonth ? Border.all(color: AppColors.primaryRedColor, width: 2) : null,
              color: Colors.transparent,
            ),
            child: Center(
              child: Text(
                monthNames[index],
                style: TextStyle(
                  fontFamily: "Poppins",
                  fontSize: 14.f,
                  color: AppColors.textColor,
                  fontWeight: isCurrentMonth ? FontWeight.w600 : FontWeight.normal,
                ),
                textAlign: TextAlign.center,
              ),
            ),
          ),
        );
      },
    );
  }

  // Build year picker grid
  Widget _buildYearPicker(bool isArabic, DateRangCalenderModel calendarModel) {
    final displayedDate = _calendarController.displayDate ?? DateTime.now();
    final currentYear = DateTime.now().year;

    int displayedYear;
    int currentDisplayYear;
    int startYear;

    if (calendarModel.isHijri) {
      // For Hijri calendar
      final hijriDisplayed = _currentHijriDisplay ?? calendarModel.gregorianToHijri(displayedDate);
      final hijriCurrent = calendarModel.gregorianToHijri(DateTime.now());
      displayedYear = hijriDisplayed.year;
      currentDisplayYear = hijriCurrent.year;
      startYear = (displayedYear ~/ 12) * 12;
    } else {
      // For Gregorian calendar
      displayedYear = displayedDate.year;
      currentDisplayYear = currentYear;
      startYear = (displayedYear ~/ 12) * 12;
    }

    return GridView.builder(
      padding: EdgeInsets.all(8.h),
      gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
        crossAxisCount: 3,
        childAspectRatio: 2.5,
        crossAxisSpacing: 8.h,
        mainAxisSpacing: 8.h,
      ),
      itemCount: 12,
      itemBuilder: (context, index) {
        final year = startYear + index;
        final isCurrentYear = currentDisplayYear == year;

        return GestureDetector(
          onTap: () {
            // Update the displayed year based on calendar type
            if (calendarModel.isHijri) {
              // Convert Hijri year to Gregorian date
              try {
                final currentHijriMonth = _currentHijriDisplay?.month ?? calendarModel.gregorianToHijri(displayedDate).month;
                final hijriDate = HijriGregDate(day: 1, month: currentHijriMonth, year: year);
                final gregorianDate = calendarModel.hijriToGregorian(hijriDate);
                _calendarController.displayDate = gregorianDate;
                // Track the Hijri month/year for accurate header display
                _currentHijriDisplay = hijriDate;
              } catch (e) {
                // Fallback if conversion fails
                _calendarController.displayDate = DateTime(displayedDate.year, displayedDate.month, 1);
              }
            } else {
              // Gregorian year - direct update
              _calendarController.displayDate = DateTime(year, displayedDate.month, 1);
            }

            // Switch back to date view
            setState(() {
              _viewMode = PickerViewMode.date;
            });
          },
          child: Container(
            decoration: BoxDecoration(
              borderRadius: BorderRadius.circular(8.h),
              border: isCurrentYear ? Border.all(color: AppColors.primaryRedColor, width: 2) : null,
              color: Colors.transparent,
            ),
            child: Center(
              child: Text(
                year.toString(),
                style: TextStyle(
                  fontFamily: "Poppins",
                  fontSize: 14.f,
                  color: AppColors.textColor,
                  fontWeight: isCurrentYear ? FontWeight.w600 : FontWeight.normal,
                ),
                textAlign: TextAlign.center,
              ),
            ),
          ),
        );
      },
    );
  }

  fromDateComponent() {
    return Consumer<DateRangeSelectorRangeViewModel>(
      builder: (_, model, __) {
        return displayDate(LocaleKeys.startDate.tr(context: context), model.getDateString(model.fromDate), model.fromDate == null);
      },
    );
  }

  toDateComponent() {
    return Consumer<DateRangeSelectorRangeViewModel>(
      builder: (_, model, __) {
        return displayDate(LocaleKeys.endDate.tr(context: context), model.getDateString(model.toDate), model.toDate == null);
      },
    );
  }

  displayDate(String label, String? date, bool isNotSelected) => Expanded(
    child: Row(
      spacing: 12.h,
      children: [
        Utils.buildSvgWithAssets(icon: AppAssets.rangeCalendar, iconColor: isNotSelected ? AppColors.borderOnlyColor : AppColors.blackColor, height: 24, width: 24),
        Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Text(
              label,
              style: TextStyle(
                color: AppColors.inputLabelTextColor,
                fontSize: 12.f,
                fontWeight: FontWeight.w600,
              ),
            ),
            Text(
              date!,
              style: TextStyle(
                color: AppColors.textColor,
                fontSize: 14.f,
                fontWeight: FontWeight.w600,
              ),
            )
          ],
        )
      ],
    ),
  );

  selectionChip(DateRangeSelectorRangeViewModel model) {
    return Row(
      spacing: 8.h,
      children: [
        AppCustomChipWidget(
          labelText: LocaleKeys.thisWeek.tr(context: context),
          backgroundColor: model.currentlySelectedRange == Range.WEEKLY ? AppColors.primaryRedColor.withOpacity(0.1) : AppColors.whiteColor,
          shape: RoundedRectangleBorder(
              side: BorderSide(
                color: model.currentlySelectedRange == Range.WEEKLY ? AppColors.primaryRedBorderColor : AppColors.chipBorderColorOpacity20,
                width: 1,
              ),
              borderRadius: BorderRadius.circular(10)),
        ).onPress(() {
          _calendarController.selectedRange = null;
          model.currentlySelectedRange = Range.WEEKLY;
          model.calculateDatesFromRange();
        }),
        AppCustomChipWidget(
          labelText: LocaleKeys.lastMonth.tr(context: context),
          backgroundColor: model.currentlySelectedRange == Range.LAST_MONTH ? AppColors.primaryRedColor.withOpacity(0.1) : AppColors.whiteColor,
          shape: RoundedRectangleBorder(
              side: BorderSide(
                color: model.currentlySelectedRange == Range.LAST_MONTH ? AppColors.primaryRedBorderColor : AppColors.chipBorderColorOpacity20,
                width: 1,
              ),
              borderRadius: BorderRadius.circular(10)),
        ).onPress(() {
          _calendarController.selectedRange = null;
          model.currentlySelectedRange = Range.LAST_MONTH;
          model.calculateDatesFromRange();
        }),
        AppCustomChipWidget(
          labelText: LocaleKeys.lastSixMonths.tr(context: context),
          backgroundColor: model.currentlySelectedRange == Range.LAST_6MONTH ? AppColors.primaryRedColor.withOpacity(0.1) : AppColors.whiteColor,
          shape: RoundedRectangleBorder(
              side: BorderSide(
                color: model.currentlySelectedRange == Range.LAST_6MONTH ? AppColors.primaryRedBorderColor : AppColors.chipBorderColorOpacity20,
                width: 1,
              ),
              borderRadius: BorderRadius.circular(10)),
          isEnglishOnly: true,
        ).onPress(() {
          _calendarController.selectedRange = null;
          model.currentlySelectedRange = Range.LAST_6MONTH;
          model.calculateDatesFromRange();
        }),
        AppCustomChipWidget(
          richText: Row(
            children: [
              "${LocaleKeys.year.tr(context: context)} ".toText10(),
              model.getCurrentYear.toString().toText10(isEnglishOnly: true),
            ],
          ),
          labelText: "${LocaleKeys.year.tr(context: context)} ${model.getCurrentYear}",
          backgroundColor: model.currentlySelectedRange == Range.THIS_YEAR ? AppColors.primaryRedColor.withOpacity(0.1) : AppColors.whiteColor,
          shape: RoundedRectangleBorder(
              side: BorderSide(
                color: model.currentlySelectedRange == Range.THIS_YEAR ? AppColors.primaryRedBorderColor : AppColors.chipBorderColorOpacity20,
                width: 1,
              ),
              borderRadius: BorderRadius.circular(10)),
          isEnglishOnly: true,
        ).onPress(() {
          _calendarController.selectedRange = null;
          model.currentlySelectedRange = Range.THIS_YEAR;
          model.calculateDatesFromRange();
        }),
      ],
    );
  }
}
