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

import '../model/dropdown_option.dart';

class SearchableDropdown extends StatelessWidget {
  final String label;
  final String? value;
  final List<DropdownOption> items;
  final Function(String?) onChanged;
  final String? Function(String?)? validator;
  final bool enabled;

  const SearchableDropdown({
    super.key,
    required this.label,
    required this.value,
    required this.items,
    required this.onChanged,
    this.validator,
    this.enabled = true,
  });

  @override
  Widget build(BuildContext context) {
    return DropdownSearch<DropdownOption>(
      // items: items,
      selectedItem: items.where((item) => item.value == value).firstOrNull,
      itemAsString: (item) => item.label,
      onChanged: (item) => onChanged(item?.value),
      enabled: enabled,
      // dropdownDecoratorProps: DropDownDecoratorProps(
      //   dropdownSearchDecoration: InputDecoration(
      //     labelText: label,
      //     border: const OutlineInputBorder(),
      //     contentPadding: const EdgeInsets.symmetric(horizontal: 10, vertical: 8),
      //   ),
      // ),
      popupProps: PopupProps.menu(
        showSearchBox: true,
        searchFieldProps: const TextFieldProps(
          decoration: InputDecoration(
            hintText: 'Search...',
            prefixIcon: Icon(Icons.search),
            border: OutlineInputBorder(),
            contentPadding: EdgeInsets.symmetric(horizontal: 10, vertical: 8),
          ),
        ),
        // itemBuilder: (context, item, isSelected) {
        //   return Container(
        //     padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 12),
        //     decoration: BoxDecoration(
        //       color: isSelected ? const Color(0xFFe3f2fd) : null,
        //     ),
        //     child: Text(
        //       item.label,
        //       style: TextStyle(
        //         fontSize: 13,
        //         fontWeight: isSelected ? FontWeight.w600 : FontWeight.normal,
        //       ),
        //     ),
        //   );
        // },
        menuProps: const MenuProps(
          backgroundColor: Colors.white,
          elevation: 8,
          borderRadius: BorderRadius.all(Radius.circular(4)),
        ),
        searchDelay: const Duration(milliseconds: 300),
        emptyBuilder: (context, searchEntry) {
          return const Center(
            child: Padding(
              padding: EdgeInsets.all(20),
              child: Text(
                'No items found',
                style: TextStyle(color: Colors.grey, fontSize: 13),
              ),
            ),
          );
        },
      ),
      compareFn: (item1, item2) => item1.value == item2.value,
      // validator: validator,
      dropdownBuilder: (context, selectedItem) {
        return Text(
          selectedItem?.label ?? '',
          style: const TextStyle(fontSize: 13),
        );
      },
    );
  }
}
