import 'dart:developer';

import 'package:flutter/material.dart';
import 'package:intl/intl.dart';
import 'package:provider/provider.dart';
import 'package:test_sa/dashboard_latest/dashboard_provider.dart';
import 'package:test_sa/extensions/int_extensions.dart';
import 'package:test_sa/extensions/text_extensions.dart';
import 'package:test_sa/models/enums/user_types.dart';
import 'package:test_sa/new_views/app_style/app_color.dart';

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

  @override
  State<WeeklyCalendarFragment> createState() => _WeeklyCalendarFragmentState();
}

class _WeeklyCalendarFragmentState extends State<WeeklyCalendarFragment> {

  @override
  Widget build(BuildContext context) {
    List<DateTime> weekDates = getWeekDates();

    return Consumer<DashBoardProvider>(
      builder: (context, dashBoardProvider, _) => GridView.builder(
        padding: EdgeInsets.zero,
        physics: const NeverScrollableScrollPhysics(),
        shrinkWrap: true,
        gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(
          crossAxisCount: 7,
          childAspectRatio: 60 / 80,
          crossAxisSpacing: 4,
          // mainAxisSpacing: 4,
        ),
        itemCount: weekDates.length,
        itemBuilder: (context, index) {
          DateTime currentDate = weekDates[index];
          String formattedDay = DateFormat('EEE').format(currentDate);
          String formattedDate = DateFormat('dd MMM').format(currentDate);

          // Check if the current date is selected
          bool isSelected = dashBoardProvider.upcomingFilterSelectedDate.day == currentDate.day && dashBoardProvider.upcomingFilterSelectedDate.month == currentDate.month && dashBoardProvider.upcomingFilterSelectedDate.year == currentDate.year;

          return listItem(
            formattedDate: formattedDate,
            formattedDay: formattedDay,
            context: context,
            isLoading: dashBoardProvider.isAllCountLoading,
            currentDate: currentDate,
            isSelected: isSelected,
            onSelect: () {
              dashBoardProvider.upcomingFilterSelectedDate = currentDate;
              // setState(() {
              //   selectedDate = currentDate; // Update selected date on tap
              // });
              log('selected date:${dashBoardProvider.upcomingFilterSelectedDate.toIso8601String()}');
              dashBoardProvider.resetRequestDataList();
              dashBoardProvider.getRequestDetail(usersType: UsersTypes.engineer, date: dashBoardProvider.upcomingFilterSelectedDate.toIso8601String(), status: 0);
            },
          );
        },
      ),
    );
  }

  // Function to generate a list of dates for 3 days before and 3 days after the current date
  List<DateTime> getWeekDates() {
    DateTime today = DateTime.now();
    List<DateTime> weekDates = [];

    for (int i = -3; i <= 3; i++) {
      weekDates.add(today.add(Duration(days: i)));
    }

    return weekDates;
  }

  Widget listItem({
    required String formattedDate,
    required String formattedDay,
    required BuildContext context,
    required DateTime currentDate,
    required bool isLoading,
    required bool isSelected, // To check if this item is selected
    required VoidCallback onSelect, // Callback for tap
  }) {
    return GestureDetector(
      onTap: isLoading ? null : onSelect,
      child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          Container(
            padding: EdgeInsets.symmetric(vertical: 18.toScreenHeight),
            width: double.infinity,
            decoration: ShapeDecoration(
              color: AppColor.background(context),
              shape: RoundedRectangleBorder(
                borderRadius: BorderRadius.circular(10),
                side: isSelected
                    ? const BorderSide(color: AppColor.primary10, width: 1.5) // Blue border if selected
                    : BorderSide.none,
              ),
              shadows: [
                BoxShadow(
                  color: Colors.black.withOpacity(0.03),
                  blurRadius: 5,
                  offset: const Offset(0, 0),
                  spreadRadius: 0,
                ),
              ],
            ),
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.center,
              children: [
                Text(
                  formattedDay,
                  style: AppTextStyles.tinyFont2.copyWith(
                    color: isSelected ? AppColor.black20 : AppColor.neutral170, // Blue text if selected
                  ),
                ),
                Text(
                  formattedDate,
                  style: AppTextStyles.tinyFont2.copyWith(
                    color: isSelected ? AppColor.black20 : AppColor.neutral170, // Blue text if selected
                  ),
                ),
              ],
            ),
          ),
        ],
      ),
    );
  }
}
