import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';

/// Search bar with filter button
class SearchFilterBar extends StatelessWidget {
  final TextEditingController? controller;
  final String hintText;
  final ValueChanged<String>? onChanged;
  final VoidCallback? onFilterTap;
  final bool showFilter;
  final int? activeFilterCount;
  final VoidCallback? onClear;

  const SearchFilterBar({
    super.key,
    this.controller,
    this.hintText = 'Search...',
    this.onChanged,
    this.onFilterTap,
    this.showFilter = true,
    this.activeFilterCount,
    this.onClear,
  });

  @override
  Widget build(BuildContext context) {
    return Container(
      padding: EdgeInsets.symmetric(horizontal: 16.w, vertical: 8.h),
      child: Row(
        children: [
          // Search field
          Expanded(
            child: Container(
              height: 48.h,
              decoration: BoxDecoration(
                color: Colors.grey.shade100,
                borderRadius: BorderRadius.circular(24.r),
                border: Border.all(color: Colors.grey.shade300),
              ),
              child: TextField(
                controller: controller,
                onChanged: onChanged,
                style: TextStyle(fontSize: 16.sp),
                decoration: InputDecoration(
                  hintText: hintText,
                  hintStyle: TextStyle(
                    color: Colors.grey.shade500,
                    fontSize: 16.sp,
                  ),
                  prefixIcon: Icon(
                    Icons.search_rounded,
                    color: Colors.grey.shade600,
                    size: 24.w,
                  ),
                  suffixIcon: controller?.text.isNotEmpty ?? false
                      ? IconButton(
                          icon: Icon(
                            Icons.clear_rounded,
                            color: Colors.grey.shade600,
                            size: 20.w,
                          ),
                          onPressed: () {
                            controller?.clear();
                            if (onClear != null) onClear!();
                            if (onChanged != null) onChanged!('');
                          },
                        )
                      : null,
                  border: InputBorder.none,
                  contentPadding: EdgeInsets.symmetric(
                    horizontal: 16.w,
                    vertical: 12.h,
                  ),
                ),
              ),
            ),
          ),

          // Filter button
          if (showFilter) ...[
            SizedBox(width: 12.w),
            Material(
              color: activeFilterCount != null && activeFilterCount! > 0
                  ? Colors.green.shade600
                  : Colors.grey.shade100,
              borderRadius: BorderRadius.circular(24.r),
              child: InkWell(
                onTap: onFilterTap,
                borderRadius: BorderRadius.circular(24.r),
                child: Container(
                  height: 48.h,
                  width: 48.w,
                  padding: EdgeInsets.all(12.w),
                  child: Stack(
                    children: [
                      Center(
                        child: Icon(
                          Icons.filter_list_rounded,
                          color: activeFilterCount != null && activeFilterCount! > 0
                              ? Colors.white
                              : Colors.grey.shade700,
                          size: 24.w,
                        ),
                      ),
                      if (activeFilterCount != null && activeFilterCount! > 0)
                        Positioned(
                          top: 0,
                          right: 0,
                          child: Container(
                            padding: EdgeInsets.all(4.w),
                            decoration: BoxDecoration(
                              color: Colors.red.shade600,
                              shape: BoxShape.circle,
                            ),
                            constraints: BoxConstraints(
                              minWidth: 16.w,
                              minHeight: 16.h,
                            ),
                            child: Text(
                              activeFilterCount.toString(),
                              style: TextStyle(
                                color: Colors.white,
                                fontSize: 10.sp,
                                fontWeight: FontWeight.bold,
                              ),
                              textAlign: TextAlign.center,
                            ),
                          ),
                        ),
                    ],
                  ),
                ),
              ),
            ),
          ],
        ],
      ),
    );
  }
}

/// Filter chip for selected filters
class FilterChip extends StatelessWidget {
  final String label;
  final VoidCallback onDeleted;
  final Color? color;

  const FilterChip({
    super.key,
    required this.label,
    required this.onDeleted,
    this.color,
  });

  @override
  Widget build(BuildContext context) {
    final chipColor = color ?? Colors.green.shade600;

    return Container(
      margin: EdgeInsets.only(right: 8.w, bottom: 8.h),
      padding: EdgeInsets.symmetric(horizontal: 12.w, vertical: 6.h),
      decoration: BoxDecoration(
        color: chipColor.withOpacity(0.1),
        borderRadius: BorderRadius.circular(16.r),
        border: Border.all(color: chipColor),
      ),
      child: Row(
        mainAxisSize: MainAxisSize.min,
        children: [
          Text(
            label,
            style: TextStyle(
              color: chipColor,
              fontSize: 14.sp,
              fontWeight: FontWeight.w600,
            ),
          ),
          SizedBox(width: 8.w),
          GestureDetector(
            onTap: onDeleted,
            child: Icon(
              Icons.close_rounded,
              size: 16.w,
              color: chipColor,
            ),
          ),
        ],
      ),
    );
  }
}

/// Active filters display bar
class ActiveFiltersBar extends StatelessWidget {
  final List<FilterChipData> filters;
  final VoidCallback onClearAll;

  const ActiveFiltersBar({
    super.key,
    required this.filters,
    required this.onClearAll,
  });

  @override
  Widget build(BuildContext context) {
    if (filters.isEmpty) return const SizedBox.shrink();

    return Container(
      padding: EdgeInsets.symmetric(horizontal: 16.w, vertical: 8.h),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Row(
            children: [
              Text(
                'Active Filters',
                style: TextStyle(
                  fontSize: 14.sp,
                  fontWeight: FontWeight.w600,
                  color: Colors.grey.shade700,
                ),
              ),
              const Spacer(),
              TextButton(
                onPressed: onClearAll,
                style: TextButton.styleFrom(
                  padding: EdgeInsets.symmetric(horizontal: 12.w, vertical: 4.h),
                ),
                child: Text(
                  'Clear All',
                  style: TextStyle(
                    fontSize: 14.sp,
                    color: Colors.red.shade600,
                    fontWeight: FontWeight.w600,
                  ),
                ),
              ),
            ],
          ),
          SizedBox(height: 8.h),
          Wrap(
            children: filters.map((filter) {
              return FilterChip(
                label: filter.label,
                onDeleted: filter.onDeleted,
                color: filter.color,
              );
            }).toList(),
          ),
        ],
      ),
    );
  }
}

/// Data class for filter chips
class FilterChipData {
  final String label;
  final VoidCallback onDeleted;
  final Color? color;

  FilterChipData({
    required this.label,
    required this.onDeleted,
    this.color,
  });
}

/// Filter bottom sheet dialog
class FilterBottomSheet extends StatefulWidget {
  final List<FilterOption> options;
  final List<String> selectedOptions;
  final ValueChanged<List<String>> onApply;

  const FilterBottomSheet({
    super.key,
    required this.options,
    required this.selectedOptions,
    required this.onApply,
  });

  @override
  State<FilterBottomSheet> createState() => _FilterBottomSheetState();
}

class _FilterBottomSheetState extends State<FilterBottomSheet> {
  late List<String> _tempSelected;

  @override
  void initState() {
    super.initState();
    _tempSelected = List.from(widget.selectedOptions);
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      padding: EdgeInsets.only(
        top: 20.h,
        left: 20.w,
        right: 20.w,
        bottom: MediaQuery.of(context).viewInsets.bottom + 20.h,
      ),
      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.vertical(top: Radius.circular(24.r)),
      ),
      child: Column(
        mainAxisSize: MainAxisSize.min,
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          // Header
          Row(
            children: [
              Text(
                'Filter Options',
                style: TextStyle(
                  fontSize: 20.sp,
                  fontWeight: FontWeight.bold,
                ),
              ),
              const Spacer(),
              IconButton(
                icon: Icon(Icons.close_rounded, size: 24.w),
                onPressed: () => Navigator.pop(context),
              ),
            ],
          ),
          SizedBox(height: 16.h),

          // Filter options
          ...widget.options.map((option) {
            final isSelected = _tempSelected.contains(option.value);
            return CheckboxListTile(
              value: isSelected,
              onChanged: (value) {
                setState(() {
                  if (value == true) {
                    _tempSelected.add(option.value);
                  } else {
                    _tempSelected.remove(option.value);
                  }
                });
              },
              title: Text(
                option.label,
                style: TextStyle(fontSize: 16.sp),
              ),
              subtitle: option.description != null
                  ? Text(
                      option.description!,
                      style: TextStyle(fontSize: 14.sp),
                    )
                  : null,
              activeColor: Colors.green.shade600,
              controlAffinity: ListTileControlAffinity.leading,
              contentPadding: EdgeInsets.zero,
            );
          }).toList(),
          SizedBox(height: 16.h),

          // Action buttons
          Row(
            children: [
              Expanded(
                child: OutlinedButton(
                  onPressed: () {
                    setState(() => _tempSelected.clear());
                  },
                  style: OutlinedButton.styleFrom(
                    padding: EdgeInsets.symmetric(vertical: 14.h),
                    shape: RoundedRectangleBorder(
                      borderRadius: BorderRadius.circular(12.r),
                    ),
                  ),
                  child: Text(
                    'Reset',
                    style: TextStyle(fontSize: 16.sp),
                  ),
                ),
              ),
              SizedBox(width: 12.w),
              Expanded(
                child: ElevatedButton(
                  onPressed: () {
                    widget.onApply(_tempSelected);
                    Navigator.pop(context);
                  },
                  style: ElevatedButton.styleFrom(
                    backgroundColor: Colors.green.shade600,
                    foregroundColor: Colors.white,
                    padding: EdgeInsets.symmetric(vertical: 14.h),
                    shape: RoundedRectangleBorder(
                      borderRadius: BorderRadius.circular(12.r),
                    ),
                  ),
                  child: Text(
                    'Apply',
                    style: TextStyle(fontSize: 16.sp, fontWeight: FontWeight.w600),
                  ),
                ),
              ),
            ],
          ),
        ],
      ),
    );
  }
}

/// Filter option data class
class FilterOption {
  final String label;
  final String value;
  final String? description;

  FilterOption({
    required this.label,
    required this.value,
    this.description,
  });
}

