import 'package:flutter/material.dart';
import 'package:jiffy/jiffy.dart';
import 'package:tp5/roster/widgets/w_month.dart';
import 'package:scroll_to_index/scroll_to_index.dart';

class HorizontalMonth extends StatefulWidget {
  const HorizontalMonth(
      {super.key,
      required this.start,
      required this.end,
      required this.onmonthclick,
      required this.selectedmonth});
  final Jiffy start;
  final Jiffy end;
  final void Function(Jiffy date) onmonthclick;
  final List<Jiffy> selectedmonth;

  @override
  State<HorizontalMonth> createState() => _WMonthsState();
}

class _WMonthsState extends State<HorizontalMonth> {
  final AutoScrollController scrollCtrl = AutoScrollController();
  List<Jiffy> dates = [];

  @override
  void initState() {
    Jiffy ijiffy = widget.start;
    while (ijiffy.isSameOrBefore(widget.end)) {
      if (!(dates
          .map((Jiffy e) => e.format(pattern: "MMMyy"))
          .contains(ijiffy.format(pattern: "MMMyy")))) {
        dates.add(ijiffy);
      }

      ijiffy = ijiffy.add(days: 1);
    }
    dates = dates.reversed.toList();

    int index = 0;
    for (var date in dates) {
      if ((widget.selectedmonth).any((month) =>
          month.isSameOrAfter(date.startOf(Unit.month)) &&
          month.isSameOrBefore(date.endOf(Unit.month)))) {
        break;
      }
      index++;
    }
    Future.delayed(const Duration(milliseconds: 300)).then((value) =>
        scrollCtrl.scrollToIndex(index,
            duration: const Duration(milliseconds: 1000),
            preferPosition: AutoScrollPosition.middle));

    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return SizedBox(
      height: 90,
      child: ListView.builder(
          controller: scrollCtrl,
          padding: const EdgeInsets.all(5),
          scrollDirection: Axis.horizontal,
          itemCount: dates.length,
          itemBuilder: (_, i) => AutoScrollTag(
              key: ValueKey(i),
              controller: scrollCtrl,
              index: i,
              child: InkWell(
                onTap: () => widget.onmonthclick(dates.elementAt(i)),
                child: WMonth(
                  date: dates.elementAt(i),
                  selected: widget.selectedmonth.any((Jiffy j) => (j
                          .isSameOrAfter(
                              dates.elementAt(i).startOf(Unit.month)) &&
                      j.isSameOrBefore(dates.elementAt(i).endOf(Unit.month)))),
                ),
              ))),
    );
  }
}
