import 'package:calendar_date_picker2/calendar_date_picker2.dart';
import 'package:easy_localization/easy_localization.dart';
import 'package:flutter/material.dart';
import 'package:gap/gap.dart';
import 'package:krow/core/presentation/gen/assets.gen.dart';
import 'package:krow/core/presentation/styles/kw_text_styles.dart';
import 'package:krow/core/presentation/styles/theme.dart';

class ScheduleCalendar extends StatefulWidget {
  const ScheduleCalendar({
    super.key,
    required this.selectedDates,
    required this.onDateSelected,
    required this.containsScheduleForDate,
    required this.disabled,
  });

  // static const _monthNames = [
  //   'Jan',
  //   'Feb',
  //   'Mar',
  //   'Apr',
  //   'May',
  //   'Jun',
  //   'Jul',
  //   'Aug',
  //   'Sep',
  //   'Oct',
  //   'Nov',
  //   'Dec',
  // ];


  final List<DateTime> selectedDates;
  final void Function(List<DateTime> value) onDateSelected;
  final bool Function(DateTime date) containsScheduleForDate;
  final bool disabled;

  @override
  State<ScheduleCalendar> createState() => _ScheduleCalendarState();
}

class _ScheduleCalendarState extends State<ScheduleCalendar> {
  final currentDate = DateTime.now();
  final selectedTextStyle = AppTextStyles.bodyMediumSmb.copyWith(
    color: AppColors.grayWhite,
  );
  final dayTextStyle = AppTextStyles.bodyMediumReg.copyWith(
    color: AppColors.bgColorDark,
  );

  late List<DateTime> _selectedDates =
      _getStateSelectedDates(widget.selectedDates);

  List<DateTime> _getStateSelectedDates(List<DateTime> selectedDates) {
    if (selectedDates.isEmpty) return [];

    return [
      selectedDates.first,
      if (selectedDates.length > 1) selectedDates.last,
    ];
  }

  @override
  void didUpdateWidget(covariant ScheduleCalendar oldWidget) {
    _selectedDates = _getStateSelectedDates(widget.selectedDates);
    super.didUpdateWidget(oldWidget);
  }

  @override
  Widget build(BuildContext context) {
    return IgnorePointer(
      ignoring: widget.disabled,
      child: CalendarDatePicker2(
        value: _selectedDates,
        config: CalendarDatePicker2Config(
          calendarType: CalendarDatePicker2Type.range,
          selectedRangeHighlightColor: AppColors.tintGray,
          selectedDayTextStyle: selectedTextStyle,
          dayTextStyle: dayTextStyle,

          selectedMonthTextStyle: selectedTextStyle,
          selectedYearTextStyle: selectedTextStyle,
          selectedDayHighlightColor: AppColors.bgColorDark,
          centerAlignModePicker: true,
          monthTextStyle: dayTextStyle,
          weekdayLabelBuilder: _dayWeekBuilder,
          dayBuilder: _dayBuilder,
          monthBuilder: _monthBuilder,
          yearBuilder: _yearBuilder,
          controlsTextStyle: AppTextStyles.headingH3,
          nextMonthIcon: Assets.images.icons.caretRight.svg(),
          lastMonthIcon: Assets.images.icons.caretLeft.svg(),
          customModePickerIcon: Padding(
            padding: const EdgeInsets.only(left: 4),
            child: Assets.images.icons.caretDown.svg(),
          ),
          // modePickerBuilder: _controlBuilder,
        ),
        onValueChanged: widget.onDateSelected,
      ),
    );
  }

  Widget? _monthBuilder({
    required int month,
    TextStyle? textStyle,
    BoxDecoration? decoration,
    bool? isSelected,
    bool? isDisabled,
    bool? isCurrentMonth,
  }) {
    return Center(
      child: Container(
        margin: const EdgeInsets.only(top: 12),
        height: 46,
        decoration: BoxDecoration(
          color: isSelected == true ? AppColors.blackDarkBgBody : null,
          borderRadius: BorderRadius.circular(23),
          border: Border.all(
            color: AppColors.grayStroke,
            width: isSelected == true ? 0 : 1,
          ),
        ),
        child: Center(
          child: Text(
            DateFormat.MMM(context.locale.toLanguageTag()).format(
              DateFormat('M').parse(month.toString()),
            ),
            style: isSelected == true
                ? AppTextStyles.bodyMediumMed
                    .copyWith(color: AppColors.grayWhite)
                : AppTextStyles.bodyMediumReg
                    .copyWith(color: AppColors.blackGray),
            textAlign: TextAlign.center,
          ),
        ),
      ),
    );
  }

  Widget? _yearBuilder({
    required int year,
    TextStyle? textStyle,
    BoxDecoration? decoration,
    bool? isSelected,
    bool? isDisabled,
    bool? isCurrentYear,
  }) {
    return Center(
      child: Text(
        year.toString(),
        style: dayTextStyle,
        textAlign: TextAlign.center,
      ),
    );
  }

  Widget? _dayBuilder({
    required DateTime date,
    TextStyle? textStyle,
    BoxDecoration? decoration,
    bool? isSelected,
    bool? isDisabled,
    bool? isToday,
  }) {
    final eventExist = widget.containsScheduleForDate(date);

    return Center(
      child: Container(
        margin: const EdgeInsets.only(left: 2, right: 2),
        alignment: Alignment.center,
        decoration: BoxDecoration(
          color: isSelected == true ? AppColors.bgColorDark : null,
          borderRadius: BorderRadius.circular(20),
        ),
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            if (eventExist) const Gap(5),
            Text(
              date.day.toString(),
              style: isSelected == true
                  ? selectedTextStyle
                  : AppTextStyles.bodyMediumReg.copyWith(
                      color: _isPast(date)
                          ? AppColors.blackCaptionText
                          : AppColors.bgColorDark,
                    ),
              textAlign: TextAlign.center,
            ),
            if (eventExist) ...[
              const Gap(1),
              DecoratedBox(
                decoration: BoxDecoration(
                  color: isSelected == true
                      ? AppColors.grayWhite
                      : AppColors.bgColorDark,
                  borderRadius: BorderRadius.circular(2),
                ),
                child: const SizedBox(
                  height: 4,
                  width: 4,
                ),
              ),
            ],
            const Gap(2),
          ],
        ),
      ),
    );
  }

  bool _isPast(DateTime date) {
    return date.isBefore(
      DateTime(currentDate.year, currentDate.month, currentDate.day),
    );
  }

  Widget? _dayWeekBuilder({
    required int weekday,
    bool? isScrollViewTopHeader,
  }) {
    print(DateFormat('d', 'en').parse((weekday).toString()));
    return Text(
      DateFormat.E(context.locale.toLanguageTag()).format(
          DateTime(2020, 1, (5 + weekday)) // 5 is Monday, so we start from there),
      ),
      style: AppTextStyles.bodyMediumSmb.copyWith(
        color: AppColors.bgColorDark,
      ),
      textAlign: TextAlign.center,
    );
  }
}
