import 'package:flutter/material.dart';

import '../../../../components/field/date_range_picker_field.dart';
import 'status_tile.dart';

class FilterHeaderDelegate extends SliverPersistentHeaderDelegate {
  final Color backgroundColor;
  final EdgeInsets padding;
  final DateTime? startDate;
  final DateTime? endDate;
  final List<String> filterOptions;
  final String selectedFilter;
  final Function(DateTime?, DateTime?) onDateChanged;
  final Function(String) onFilterChanged;

  FilterHeaderDelegate({
    required this.backgroundColor,
    required this.padding,
    required this.startDate,
    required this.endDate,
    required this.filterOptions,
    required this.selectedFilter,
    required this.onDateChanged,
    required this.onFilterChanged,
  });

  @override
  double get minExtent => 130;

  @override
  double get maxExtent => 130;

  @override
  Widget build(
    BuildContext context,
    double shrinkOffset,
    bool overlapsContent,
  ) {
    print('FilterHeaderDelegate build called'); // Debug log
    return Container(
      color: backgroundColor,
      padding: padding,
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Padding(
            padding: const EdgeInsets.only(bottom: 8.0),
            child: DateRangePickerField(
              maxDate: DateTime.now(),
              startDate: startDate,
              endDate: endDate,
              onChanged: (start, end) {
                print(
                  'onChanged called in FilterHeaderDelegate: $start - $end',
                ); // Debug log
                onDateChanged(start, end);
              },
            ),
          ),
          Expanded(
            child: SingleChildScrollView(
              scrollDirection: Axis.horizontal,
              child: Row(
                children: filterOptions.asMap().entries.map((entry) {
                  final index = entry.key;
                  final option = entry.value;

                  return Padding(
                    padding: EdgeInsets.only(
                      right: index < filterOptions.length - 1 ? 8 : 0,
                    ),
                    child: OrderStatusTile(
                      label: option,
                      isSelected: option == selectedFilter,
                      onSelected: (isSelected) {
                        if (isSelected) {
                          onFilterChanged(option);
                        }
                      },
                    ),
                  );
                }).toList(),
              ),
            ),
          ),
        ],
      ),
    );
  }

  @override
  bool shouldRebuild(covariant FilterHeaderDelegate oldDelegate) {
    return oldDelegate.startDate != startDate ||
        oldDelegate.endDate != endDate ||
        oldDelegate.selectedFilter != selectedFilter ||
        oldDelegate.filterOptions.length != filterOptions.length ||
        oldDelegate.backgroundColor != backgroundColor;
  }
}
