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/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/date_range_selector/viewmodel/date_range_view_model.dart' show DateRangeSelectorRangeViewModel;
import 'package:provider/provider.dart';
import 'package:syncfusion_flutter_calendar/calendar.dart';
import 'package:syncfusion_flutter_datepicker/datepicker.dart';

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

class DateRangeSelector extends StatefulWidget {
  final OnRangeSelected onRangeSelected;

  const DateRangeSelector({super.key, required this.onRangeSelected});

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

class _DateRangeSelectorState extends State<DateRangeSelector> {
  late DateRangePickerController _calendarController;
  DateTime? start;
  DateTime? end;
  late DateRangeSelectorRangeViewModel model;
  @override
  void initState() {
    _calendarController = DateRangePickerController();
    scheduleMicrotask(() {
      _calendarController.selectedRange = PickerDateRange(model.fromDate,model.toDate);
    });
    super.initState();
  }

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


    _calendarController.selectedRange = PickerDateRange(model.fromDate,model.toDate);

    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(),
                      style: TextStyle(
                        color: AppColors.calenderTextColor,
                        fontSize: 14.h,
                        fontWeight: FontWeight.w500,
                        letterSpacing: -.2
                      ),
                    ).paddingSymmetrical(24.h,0.h),
                    toDateComponent(),
                  ],
                ),
                Divider(
                  color: AppColors.spacerLineColor,
                  thickness: 1,
                ).paddingOnly(bottom: 16.h, top: 16.h),
                Material(
                  color: Colors.white,
                  child: SfDateRangePicker(
                    controller: _calendarController,
                    selectionMode: DateRangePickerSelectionMode.range,
                    showNavigationArrow: true,
                    headerHeight: 40.h,
                    backgroundColor: Colors.white,
                    headerStyle: DateRangePickerHeaderStyle(
                      backgroundColor: Colors.white,
                      textAlign: TextAlign.start,
                      textStyle: TextStyle(
                        fontSize: 18.fSize,
                        fontWeight: FontWeight.w600,
                        letterSpacing: -0.46,
                        color: AppColors.primaryRedColor,
                        fontFamily: "Poppins",
                      ),
                    ),
                    monthViewSettings: DateRangePickerMonthViewSettings(
                      viewHeaderStyle: DateRangePickerViewHeaderStyle(
                        backgroundColor: Colors.white,
                        textStyle: TextStyle(
                          fontSize: 14.fSize,
                          fontWeight: FontWeight.w600,
                          letterSpacing: -0.46,
                          color: AppColors.textColor,
                        ),
                      ),
                      showTrailingAndLeadingDates: false,
                      dayFormat: "EEE",
                    ),
                    selectionShape: DateRangePickerSelectionShape.rectangle,
                    selectionRadius: 12.h,
                    selectionColor: AppColors.transparent,
                    startRangeSelectionColor: AppColors.primaryRedColor,
                    endRangeSelectionColor: AppColors.primaryRedColor,
                    rangeSelectionColor:
                        AppColors.primaryRedColor.withOpacity(0.1),
                    todayHighlightColor: Colors.transparent,
                    monthCellStyle: DateRangePickerMonthCellStyle(
                      textStyle: TextStyle(
                        fontSize: 12.fSize,
                        color: AppColors.textColor,
                      ),
                      todayTextStyle: TextStyle(
                        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(),
                            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(),
                  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),
        ],
      ),
    );
  }

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

  toDateComponent() {
    return Consumer<DateRangeSelectorRangeViewModel>(
      builder: (_, model, __) {
        return displayDate(LocaleKeys.endDate.tr(),
            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.h,
                    fontWeight: FontWeight.w500,
                  ),
                ),
                Text(
                  date!,
                  style: TextStyle(
                    color: AppColors.textColor,
                    fontSize: 14.h,
                    fontWeight: FontWeight.w500,
                  ),
                )
              ],
            )
          ],
        ),
  );

  selectionChip(DateRangeSelectorRangeViewModel model) {
    return Row(
      spacing: 8.h,
      children: [
        AppCustomChipWidget(
          labelText: "This Week".needTranslation,
          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: "Last Month".needTranslation,
          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: "Last 6 Months".needTranslation,
          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)),
        ).onPress((){
          _calendarController.selectedRange = null;
          model.currentlySelectedRange = Range.LAST_6MONTH;
          model.calculateDatesFromRange();

        }),
        AppCustomChipWidget(
          labelText: "Year ${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)),
        ).onPress((){
          _calendarController.selectedRange = null;
          model.currentlySelectedRange = Range.THIS_YEAR;
          model.calculateDatesFromRange();

        }),
      ],
    );
  }
}
