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

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

class Commondaterangefilter {
  Dropdowntheme ddtheme = Dropdowntheme();
  final List<String> filterItems = [
    'Today',
    'Yesterday',
    'This Month',
    'Past 7 days',
    'Last Month',
    'Custom',
  ];
  String? selectedValue;
  DateTimeRange? selectedDateRange;

  // 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(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(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; // Custom handled in bottom sheet
      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();

    return await showModalBottomSheet<Map<String, dynamic>>(
      context: context,
      useSafeArea: true,
      isDismissible: true,
      isScrollControlled: true,
      showDragHandle: true,
      backgroundColor: Colors.white,
      enableDrag: true,
      shape: RoundedRectangleBorder(
        borderRadius: BorderRadius.vertical(top: Radius.circular(20)),
      ),
      builder: (BuildContext context) {
        return StatefulBuilder(
          builder: (BuildContext context, StateSetter setState) {
            // Custom calendar widget
            // Widget buildCalendar() {
            //   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 = [];
            //   // Weekday headers
            //   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],
            //       ),
            //     ),
            //   )));
            //
            //   // Empty cells before the first day
            //   for (int i = 0; i < daysBefore; i++) {
            //     dayWidgets.add(Container());
            //   }
            //
            //   // Days of the month
            //   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;
            //     }
            //
            //     dayWidgets.add(
            //       GestureDetector(
            //         onTap: isOutsideRange
            //             ? null
            //             : () {
            //           setState(() {
            //             if (tempStartDate == null) {
            //               tempStartDate = currentDate;
            //             } 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: 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",
            //             ),
            //           ),
            //           // IconButton(
            //           //   icon: Icon(Icons.chevron_left, color: Colors.blue[600]),
            //           //   onPressed: displayedMonth.isAfter(DateTime(2020))
            //           //       ? () {
            //           //     setState(() {
            //           //       displayedMonth = DateTime(displayedMonth.year, displayedMonth.month - 1);
            //           //     });
            //           //   }
            //           //       : null,
            //           // ),
            //           Text(
            //             '${_monthName(displayedMonth.month)} ${displayedMonth.year}',
            //             style: 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",
            //             ),
            //           ),
            //           // IconButton(
            //           //   icon: Icon(Icons.chevron_right, color: Colors.blue[600]),
            //           //   onPressed: displayedMonth.isBefore(DateTime(2100))
            //           //       ? () {
            //           //     setState(() {
            //           //       displayedMonth = DateTime(displayedMonth.year, displayedMonth.month + 1);
            //           //     });
            //           //   }
            //           //       : null,
            //           // ),
            //         ],
            //       ),
            //       Container(
            //         height: 280,
            //         child: GridView.count(
            //           crossAxisCount: 7,
            //           childAspectRatio: 1.2,
            //           children: dayWidgets,
            //           physics: NeverScrollableScrollPhysics(),
            //         ),
            //       ),
            //     ],
            //   );
            // }
            Widget buildCalendar() {
              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 = [];
              // Weekday headers
              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],
                  ),
                ),
              )));

              // Empty cells before the first day
              for (int i = 0; i < daysBefore; i++) {
                dayWidgets.add(Container());
              }

              // Days of the month
              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) {
                          // No start date selected, set it
                          tempStartDate = currentDate;
                          tempSelectedDateRange = null;
                        } else if (tempEndDate == null) {
                          // Start date selected, set end date
                          if (currentDate.isBefore(tempStartDate!)) {
                            // If the new date is before start date, swap them
                            tempEndDate = tempStartDate;
                            tempStartDate = currentDate;
                          } else {
                            tempEndDate = currentDate;
                          }
                          tempSelectedDateRange = DateTimeRange(
                            start: tempStartDate!,
                            end: tempEndDate!,
                          );
                        } else {
                          // Both dates selected, reset to start a new range
                          tempStartDate = currentDate;
                          tempEndDate = null;
                          tempSelectedDateRange = null;
                        }
                      });
                    },
                    child: Container(
                      margin: 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: 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",
                        ),
                      ),
                    ],
                  ),
                  Container(
                    height: 280,
                    child: GridView.count(
                      crossAxisCount: 7,
                      childAspectRatio: 1.2,
                      children: dayWidgets,
                      physics: NeverScrollableScrollPhysics(),
                    ),
                  ),
                ],
              );
            }
            return SafeArea(
              child: Padding(
                padding: EdgeInsets.only(
                  top: 16,
                  left: 16,
                  right: 16,
                  bottom: MediaQuery.of(context).viewInsets.bottom,
                ),
                child: SingleChildScrollView(
                  child: Column(
                    mainAxisSize: MainAxisSize.min,
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      Text(
                        'Select Date Range',
                        style: TextStyle(fontSize: 18, fontWeight: FontWeight.bold),
                      ),
                      SizedBox(height: 16),
                      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) {
                                  return 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') ...[
                        SizedBox(height: 16),
                        Container(
                          decoration: BoxDecoration(
                            border: Border.all(color: Colors.grey[300]!),
                            borderRadius: BorderRadius.circular(12),
                          ),
                          padding: EdgeInsets.all(12),
                          child: buildCalendar(),
                        ),
                        if (tempSelectedDateRange != null)
                          Padding(
                            padding: const EdgeInsets.only(top: 12.0),
                            child: Text(
                              'Selected: ${formatDate(tempSelectedDateRange!.start)} to ${formatDate(tempSelectedDateRange!.end)}',
                              style: TextStyle(fontSize: 14, color: Colors.grey[600]),
                            ),
                          ),
                      ],
                      SizedBox(height: 16),
                      Row(
                        mainAxisAlignment: MainAxisAlignment.end,
                        children: [
                          TextButton(
                            onPressed: () => Navigator.pop(context),
                            child: Text(
                              'Cancel',
                              style: TextStyle(color: Colors.grey[600]),
                            ),
                          ),
                          SizedBox(width: 8),
                          ElevatedButton(
                            onPressed: tempSelectedDateRange != null && tempSelectedValue != null
                                ? () {
                              selectedValue = tempSelectedValue;
                              selectedDateRange = tempSelectedDateRange;
                              Navigator.pop(context, {
                                'selectedValue': tempSelectedValue,
                                'dateRange': tempSelectedDateRange,
                                'formatted': getFormattedDateRange(tempSelectedDateRange),
                              });
                            }
                                : null,
                            style: ElevatedButton.styleFrom(
                              backgroundColor: Colors.blue[600],
                              foregroundColor: Colors.white,
                              shape: RoundedRectangleBorder(
                                borderRadius: BorderRadius.circular(8),
                              ),
                            ),
                            child: Text('Apply'),
                          ),
                        ],
                      ),
                      SizedBox(height: MediaQuery.of(context).viewInsets.bottom),
                    ],
                  ),
                ),
              ),
            );
          },
        );
      },
    );
  }

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

// Widget to demonstrate usage
// class MyWidget extends StatelessWidget {
//   @override
//   Widget build(BuildContext context) {
//     return Scaffold(
//       body: Center(
//         child: InkResponse(
//           onTap: () async {
//             var cf = Commondaterangefilter();
//             var result = await cf.showFilterBottomSheet(context);
//             if (result != null) {
//               var dateRange = result['dateRange'] as DateTimeRange?;
//               print("dateRange: $dateRange");
//
//               var formatted = result['formatted'] as List<String>;
//               print("formatted: $formatted");
//
//               if (formatted.isNotEmpty) {
//                 var fromDate = formatted[0]; // From date
//                 var toDate = formatted[1]; // To date
//                 print("from_date: $fromDate");
//                 print("to_date: $toDate");
//               } else {
//                 print("No valid date range selected");
//               }
//             } else {
//               print("Bottom sheet closed without selection");
//             }
//           },
//           child: SvgPicture.asset("assets/svg/filter_ic.svg", height: 25),
//         ),
//       ),
//     );
//   }
// }