import 'package:dropdown_button2/dropdown_button2.dart';
import 'package:flutter/material.dart';
import 'package:flutter_svg/svg.dart';
import 'package:intl/intl.dart';

import '../Utils/app_colors.dart';
import '../Utils/dropdownTheme.dart';

class CommonFilter2 {
  Dropdowntheme ddtheme = Dropdowntheme();

  final List<String> filterItems = [
    'Today',
    'Yesterday',
    'This Month',
    'Past 7 days',
    'Last Month',
    'Custom',
  ];

  final List<String> typeItems = [
    "All",
    "Check In",
    "Check Out",
    "Check In/Out",
  ];

  String? selectedValue; // Date range value
  DateTimeRange? selectedDateRange;

  String? selectedType; // Type value

  // Get DateTimeRange based on filter selection
  DateTimeRange? getDateRange(String filter) {
    DateTime now = DateTime.now();
    switch (filter) {
      case 'Today':
        return DateTimeRange(
          start: DateTime(now.year, now.month, now.day),
          end: DateTime(now.year, now.month, now.day),
        );
      case 'Yesterday':
        DateTime yesterday = now.subtract(const Duration(days: 1));
        return DateTimeRange(
          start: DateTime(yesterday.year, yesterday.month, yesterday.day),
          end: DateTime(yesterday.year, yesterday.month, yesterday.day),
        );
      case 'This Month':
        return DateTimeRange(
          start: DateTime(now.year, now.month, 1),
          end: DateTime(now.year, now.month + 1, 0),
        );
      case 'Past 7 days':
        return DateTimeRange(
          start: now.subtract(const Duration(days: 6)),
          end: DateTime(now.year, now.month, now.day),
        );
      case 'Last Month':
        return DateTimeRange(
          start: DateTime(now.year, now.month - 1, 1),
          end: DateTime(now.year, now.month, 0),
        );
      case 'Custom':
        return null;
      default:
        return null;
    }
  }

  // Format a single DateTime to string
  String formatDate(DateTime date) {
    return "${date.year}-${date.month.toString().padLeft(2, '0')}-${date.day.toString().padLeft(2, '0')}";
  }

  // Get formatted date range as a list of strings
  List<String> getFormattedDateRange(DateTimeRange? dateRange) {
    if (dateRange != null) {
      return [formatDate(dateRange.start), formatDate(dateRange.end)];
    }
    return [];
  }

  Future<Map<String, dynamic>?> showFilterBottomSheet(
    BuildContext context,
  ) async {
    String? tempSelectedValue = selectedValue;
    DateTimeRange? tempSelectedDateRange = selectedDateRange;
    DateTime? tempStartDate;
    DateTime? tempEndDate;
    DateTime displayedMonth = DateTime.now();

    String? tempSelectedType = selectedType ?? "All";

    Widget buildCalendar(StateSetter setState) {
      final firstDayOfMonth = DateTime(
        displayedMonth.year,
        displayedMonth.month,
        1,
      );
      final lastDayOfMonth = DateTime(
        displayedMonth.year,
        displayedMonth.month + 1,
        0,
      );
      final firstDayOfWeek = firstDayOfMonth.weekday;
      final daysInMonth = lastDayOfMonth.day;
      final daysBefore = (firstDayOfWeek - 1) % 7;

      List<Widget> dayWidgets = [];

      final weekdays = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'];
      dayWidgets.addAll(
        weekdays.map(
          (day) => Center(
            child: Text(
              day,
              style: TextStyle(
                fontSize: 14,
                fontWeight: FontWeight.w600,
                color: Colors.grey[700],
              ),
            ),
          ),
        ),
      );

      for (int i = 0; i < daysBefore; i++) {
        dayWidgets.add(Container());
      }

      for (int day = 1; day <= daysInMonth; day++) {
        final currentDate = DateTime(
          displayedMonth.year,
          displayedMonth.month,
          day,
        );
        bool isSelected = false;
        bool isInRange = false;
        bool isOutsideRange =
            currentDate.isBefore(DateTime(2020)) ||
            currentDate.isAfter(DateTime(2100));

        if (tempStartDate != null && tempEndDate != null) {
          isSelected =
              currentDate.isAtSameMomentAs(tempStartDate!) ||
              currentDate.isAtSameMomentAs(tempEndDate!);
          isInRange =
              currentDate.isAfter(tempStartDate!) &&
              currentDate.isBefore(tempEndDate!) &&
              !isSelected;
        } else if (tempStartDate != null) {
          isSelected = currentDate.isAtSameMomentAs(tempStartDate!);
        }

        dayWidgets.add(
          GestureDetector(
            onTap:
                isOutsideRange
                    ? null
                    : () {
                      setState(() {
                        if (tempStartDate == null) {
                          tempStartDate = currentDate;
                          tempSelectedDateRange = null;
                        } else if (tempEndDate == null) {
                          if (currentDate.isBefore(tempStartDate!)) {
                            tempEndDate = tempStartDate;
                            tempStartDate = currentDate;
                          } else {
                            tempEndDate = currentDate;
                          }
                          tempSelectedDateRange = DateTimeRange(
                            start: tempStartDate!,
                            end: tempEndDate!,
                          );
                        } else {
                          tempStartDate = currentDate;
                          tempEndDate = null;
                          tempSelectedDateRange = null;
                        }
                      });
                    },
            child: Container(
              margin: const EdgeInsets.all(2),
              decoration: BoxDecoration(
                color:
                    isSelected
                        ? Colors.blue[600]
                        : isInRange
                        ? Colors.blue[100]
                        : null,
                shape: BoxShape.circle,
              ),
              child: Center(
                child: Text(
                  '$day',
                  style: TextStyle(
                    color:
                        isOutsideRange
                            ? Colors.grey[400]
                            : isSelected
                            ? Colors.white
                            : Colors.black,
                    fontWeight:
                        isSelected ? FontWeight.bold : FontWeight.normal,
                  ),
                ),
              ),
            ),
          ),
        );
      }

      return Column(
        children: [
          Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: [
              GestureDetector(
                onTap:
                    displayedMonth.isAfter(DateTime(2020))
                        ? () {
                          setState(() {
                            displayedMonth = DateTime(
                              displayedMonth.year,
                              displayedMonth.month - 1,
                            );
                          });
                        }
                        : null,
                child: SvgPicture.asset("assets/svg/arrow_left.svg"),
              ),
              Text(
                '${_monthName(displayedMonth.month)} ${displayedMonth.year}',
                style: const TextStyle(
                  fontSize: 16,
                  fontWeight: FontWeight.w600,
                ),
              ),
              GestureDetector(
                onTap:
                    displayedMonth.isBefore(DateTime(2100))
                        ? () {
                          setState(() {
                            displayedMonth = DateTime(
                              displayedMonth.year,
                              displayedMonth.month + 1,
                            );
                          });
                        }
                        : null,
                child: SvgPicture.asset("assets/svg/arrow_right_new.svg"),
              ),
            ],
          ),
          SizedBox(
            height: 280,
            child: GridView.count(
              crossAxisCount: 7,
              childAspectRatio: 1.2,
              physics: const NeverScrollableScrollPhysics(),
              children: dayWidgets,
            ),
          ),
        ],
      );
    }

    return await showModalBottomSheet<Map<String, dynamic>>(
      context: context,
      isScrollControlled: true,
      shape: const RoundedRectangleBorder(
        borderRadius: BorderRadius.vertical(top: Radius.circular(20)),
      ),
      builder: (BuildContext context) {
        return StatefulBuilder(
          builder: (BuildContext context, StateSetter setState) {
            return SafeArea(
              child: Padding(
                padding: EdgeInsets.only(
                  top: 16,
                  left: 16,
                  right: 16,
                  bottom: MediaQuery.of(context).viewInsets.bottom,
                ),
                child: SingleChildScrollView(
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      Text(
                        'Filter Attendance',
                        style: TextStyle(
                          color: AppColors.app_blue,
                          fontSize: 18,
                          fontFamily: "JakartaSemiBold",
                        ),
                      ),
                      const SizedBox(height: 20),

                      /// Type filter
                      const Text(
                        "Type",
                        style: TextStyle(
                          fontSize: 16,
                          fontWeight: FontWeight.w500,
                        ),
                      ),
                      const SizedBox(height: 8),
                      DropdownButtonHideUnderline(
                        child: Row(
                          children: [
                            Expanded(
                              child: DropdownButton2<String>(
                                isExpanded: true,
                                value: tempSelectedType,
                                items:
                                    typeItems
                                        .map(
                                          (type) => DropdownMenuItem<String>(
                                            value: type,
                                            child: Text(type),
                                          ),
                                        )
                                        .toList(),
                                onChanged: (value) {
                                  setState(() {
                                    tempSelectedType = value;
                                  });
                                },
                                buttonStyleData: ddtheme.buttonStyleData,
                                iconStyleData: ddtheme.iconStyleData,
                                menuItemStyleData: ddtheme.menuItemStyleData,
                                dropdownStyleData: ddtheme.dropdownStyleData,
                              ),
                            ),
                          ],
                        ),
                      ),
                      const SizedBox(height: 20),

                      /// Date range filter
                      const Text(
                        "Date Range",
                        style: TextStyle(
                          fontSize: 16,
                          fontWeight: FontWeight.w500,
                        ),
                      ),
                      const SizedBox(height: 8),
                      DropdownButtonHideUnderline(
                        child: Row(
                          children: [
                            Expanded(
                              child: DropdownButton2<String>(
                                isExpanded: true,
                                hint: Text(
                                  tempSelectedValue ?? 'Select Item',
                                  style: TextStyle(
                                    fontSize: 14,
                                    fontWeight: FontWeight.w400,
                                    color: Colors.black,
                                  ),
                                ),
                                items:
                                    filterItems
                                        .map(
                                          (String item) =>
                                              DropdownMenuItem<String>(
                                                value: item,
                                                child: Text(
                                                  item,
                                                  style: TextStyle(
                                                    fontSize: 14,
                                                    fontWeight: FontWeight.w400,
                                                    color: Colors.black,
                                                  ),
                                                ),
                                              ),
                                        )
                                        .toList(),
                                value: tempSelectedValue,
                                onChanged: (String? value) {
                                  if (value == null) return;
                                  setState(() {
                                    tempSelectedValue = value;
                                    if (value != 'Custom') {
                                      tempSelectedDateRange = getDateRange(
                                        value,
                                      );
                                      tempStartDate = null;
                                      tempEndDate = null;
                                    } else {
                                      tempSelectedDateRange = null;
                                      tempStartDate = null;
                                      tempEndDate = null;
                                    }
                                  });
                                },
                                buttonStyleData: ddtheme.buttonStyleData,
                                iconStyleData: ddtheme.iconStyleData,
                                menuItemStyleData: ddtheme.menuItemStyleData,
                                dropdownStyleData: ddtheme.dropdownStyleData,
                              ),
                            ),
                          ],
                        ),
                      ),

                      if (tempSelectedValue == 'Custom') ...[
                        const SizedBox(height: 16),
                        Container(
                          decoration: BoxDecoration(
                            border: Border.all(color: Colors.grey[300]!),
                            borderRadius: BorderRadius.circular(12),
                          ),
                          padding: const EdgeInsets.all(12),
                          child: buildCalendar(setState),
                        ),
                        if (tempSelectedDateRange != null)
                          Padding(
                            padding: const EdgeInsets.only(top: 12.0),
                            child: Text(
                              'Selected: ${DateFormat("dd MMM yyyy").format(tempSelectedDateRange!.start)} to ${DateFormat("dd MMM yyyy").format(tempSelectedDateRange!.end)}',
                              style: TextStyle(
                                fontSize: 14,
                                color: Colors.grey[600],
                              ),
                            ),
                          ),
                      ],

                      const SizedBox(height: 20),
                      Row(
                        mainAxisAlignment: MainAxisAlignment.end,
                        children: [
                          TextButton(
                            onPressed: () => Navigator.pop(context),
                            child: Text(
                              'Cancel',
                              style: TextStyle(color: Colors.grey[600]),
                            ),
                          ),
                          const SizedBox(width: 8),
                          ElevatedButton(
                            onPressed: () {
                              Navigator.pop(context, {
                                'type':
                                    tempSelectedType, // if you store type separately
                                'selectedValue':
                                    tempSelectedValue, // could be null
                                'dateRange':
                                    tempSelectedDateRange, // could be null
                                'formatted':
                                    tempSelectedDateRange != null
                                        ? getFormattedDateRange(
                                          tempSelectedDateRange,
                                        )
                                        : null,
                              });
                            },
                            style: ElevatedButton.styleFrom(
                              backgroundColor: Colors.blue[600],
                              foregroundColor: Colors.white,
                              shape: RoundedRectangleBorder(
                                borderRadius: BorderRadius.circular(8),
                              ),
                            ),
                            child: const Text('Apply'),
                          ),
                        ],
                      ),
                    ],
                  ),
                ),
              ),
            );
          },
        );
      },
    );
  }

  String _monthName(int month) {
    const months = [
      'January',
      'February',
      'March',
      'April',
      'May',
      'June',
      'July',
      'August',
      'September',
      'October',
      'November',
      'December',
    ];
    return months[month - 1];
  }
}
