import 'package:flutter/material.dart';
import 'package:flutter_custom_month_picker/flutter_custom_month_picker.dart';
import 'package:intl/intl.dart';
import 'package:provider/provider.dart';
import 'package:table_calendar/table_calendar.dart';
import 'package:test_sa/extensions/context_extension.dart';
import 'package:test_sa/extensions/int_extensions.dart';
import 'package:test_sa/extensions/widget_extensions.dart';

import '../../../../controllers/providers/api/all_requests_provider.dart';
import '../../../../extensions/text_extensions.dart';
import '../../../app_style/app_color.dart';
import 'calendar_header.dart';
import 'calender_days_card.dart';

class MonthlyFragment extends StatefulWidget {
  const MonthlyFragment({Key? key}) : super(key: key);

  @override
  State<MonthlyFragment> createState() => _MonthlyFragmentState();
}

class _MonthlyFragmentState extends State<MonthlyFragment> {
  late DateTime _initialDate, _firstDate, _lastDate;

  @override
  void initState() {
    super.initState();
    _initialDate = DateTime.now();
    _firstDate = DateTime.utc(2010, 10, 16);
    _lastDate = DateTime.utc(2030, 3, 14);
    Provider.of<AllRequestsProvider>(context, listen: false)
        .getCalendarRequests(from: DateTime(DateTime.now().year, DateTime.now().month, 1), to: DateTime(DateTime.now().year, DateTime.now().month + 1, 0));
  }

  @override
  Widget build(BuildContext context) {
    return SingleChildScrollView(
      padding: const EdgeInsets.only(left: 16, right: 16),
      child: Column(
        children: [
          Consumer<AllRequestsProvider>(
            builder: (context, snapshot, _) => TableCalendar(
              firstDay: _firstDate,
              lastDay: _lastDate,
              focusedDay: _initialDate,
              calendarFormat: CalendarFormat.month,
              weekendDays: const [],
              rowHeight: 45,
              availableGestures: AvailableGestures.none,
              calendarBuilders: CalendarBuilders(
                headerTitleBuilder: (context, dateTime) => CalendarHeader(dateFormat: DateFormat("MMMM, yyyy", context.isAr ? "ar" : "en"), dateTime: dateTime).onPress(() async {
                  // final result = await showDatePicker(
                  //   context: context,
                  //   initialDate: _initialDate,
                  //   firstDate: _firstDate,
                  //   lastDate: _lastDate,
                  //   initialDatePickerMode: DatePickerMode.year,
                  // );
                  showMonthPicker(context, initialSelectedMonth: _initialDate.month, initialSelectedYear: _initialDate.year, lastEnabledMonth: _lastDate.month, lastYear: _lastDate.year,
                      onSelected: (month, year) async {
                    // if (result != null) {
                    await snapshot.getCalendarRequests(from: DateTime(year, month, 1), to: DateTime(year, month + 1, 0));
                    _initialDate = DateTime(year, month);
                    setState(() {});
                    //   }
                  });
                }),
                dowBuilder: (context, dateTime) {
                  final day = DateFormat("EE", context.isAr ? "ar" : "en").format(dateTime).toUpperCase();
                  return Align(alignment: Alignment.center, child: day.bodyText(context).custom(color: context.isDark ? AppColor.neutral10 : AppColor.neutral50));
                },
                defaultBuilder: (context, dateTime, _) {
                  final day = DateFormat("d").format(dateTime);
                  return CalendarDaysCard(
                    day: day,
                    fill: snapshot.calendarRequests?.requestsDetails?.firstWhere(
                          (element) => (element.date != null) && (DateTime.tryParse(element.date!)?.difference(dateTime).inDays == 0),
                          orElse: null,
                        ) !=
                        null,
                  ).toShimmer(isShow: snapshot.isCalendarLoading, context: context);
                },
              ),
              daysOfWeekHeight: 35.toScreenHeight,
              headerStyle: const HeaderStyle(
                leftChevronVisible: false,
                rightChevronVisible: false,
                formatButtonVisible: false,
                headerPadding: EdgeInsets.all(0),
              ),
              calendarStyle: CalendarStyle(
                isTodayHighlighted: false,
                defaultTextStyle: AppTextStyles.bodyText,
                defaultDecoration: BoxDecoration(shape: BoxShape.circle, color: context.isDark ? AppColor.neutral50 : AppColor.neutral30),
              ),
            ),
          ),
          Column(
            mainAxisSize: MainAxisSize.min,
            children: [
              16.height,
              Row(
                children: [
                  const CircleAvatar(backgroundColor: AppColor.primary40, radius: 8),
                  8.width,
                  context.translation.request.heading6(context),
                ],
              ),
              16.height,

              /// TODO : TBD
              // Row(
              //   children: [
              //     const CircleAvatar(backgroundColor: AppColor.green50, radius: 8),
              //     8.width,
              //     "My Team Requests".heading6(context),
              //   ],
              // ),
            ],
          ),
        ],
      ).toShadowContainer(context),
    );
  }
}
