import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:rasadyar_core/presentation/common/app_color.dart';

class MultiSelectDropdownLogic<T> extends GetxController {
  final List<T> items;
  final T? initialValue;
  final String Function(T item)? itemToString;
  final void Function(T selected)? onChanged;

  RxBool isOpen = false.obs;
  Rx<T?> selectedItem;
  late TextEditingController searchController;
  late RxList<T> filteredItems;
  late EdgeInsets? contentPadding;
  late Widget Function(T item) itemBuilder;

  MultiSelectDropdownLogic({
    required this.items,
    this.initialValue,
    this.itemToString,
    this.onChanged,
    T? selectedItem,
    this.contentPadding,
    required this.itemBuilder,
  }) : selectedItem = Rx(selectedItem ?? initialValue);

  @override
  void onInit() {
    super.onInit();
    searchController = TextEditingController();
    filteredItems = RxList<T>(items);
  }

  void showOverlay(BuildContext context) {
    final RenderBox renderBox = (context.findRenderObject() as RenderBox);
    final size = renderBox.size;
    final offset = renderBox.localToGlobal(Offset.zero);
    final screenHeight = MediaQuery.of(context).size.height;

    final bool openUp = offset.dy + size.height + 300 > screenHeight;

    searchController.clear();
    filteredItems.value = items;

    OverlayEntry overlayEntry = OverlayEntry(
      builder: (_) => GestureDetector(
        onTap: () {
          removeOverlay();
        },
        child: Stack(
          children: [
            Positioned(
              left: offset.dx,
              top: openUp ? offset.dy - 300 - 4 : offset.dy + size.height + 4,
              width: size.width,
              child: Material(
                elevation: 4,
                borderRadius: BorderRadius.circular(8),
                child: Obx(
                  () => Container(
                    decoration: BoxDecoration(
                      color: AppColor.bgLight,
                      border: Border.all(color: AppColor.darkGreyLight),
                      borderRadius: BorderRadius.circular(8),
                    ),
                    constraints: BoxConstraints(maxHeight: 300),
                    child: Column(
                      children: [
                        Padding(
                          padding: const EdgeInsets.all(8),
                          child: TextField(
                            controller: searchController,
                            decoration: const InputDecoration(
                              hintText: 'جستجو...',
                              isDense: true,
                              contentPadding: EdgeInsets.symmetric(horizontal: 12, vertical: 8),
                              border: OutlineInputBorder(),
                            ),
                            onChanged: (query) {
                              filteredItems.value = items
                                  .where(
                                    (item) =>
                                        itemToString
                                            ?.call(item)
                                            .toLowerCase()
                                            .contains(query.toLowerCase()) ??
                                        false,
                                  )
                                  .toList();
                            },
                          ),
                        ),
                        if (filteredItems.isEmpty)
                          const Padding(
                            padding: EdgeInsets.all(16.0),
                            child: Text("نتیجه‌ای یافت نشد."),
                          ),
                        if (filteredItems.isNotEmpty)
                          Flexible(
                            child: ListView.builder(
                              itemCount: filteredItems.length,
                              itemBuilder: (context, index) {
                                var item = filteredItems[index];
                                return InkWell(
                                  onTap: () {
                                    onChanged?.call(item);
                                    selectedItem.value = item;
                                    removeOverlay();
                                  },
                                  child: Padding(
                                    padding:
                                        contentPadding ??
                                        const EdgeInsets.symmetric(horizontal: 8, vertical: 4),
                                    child: itemBuilder(item),
                                  ),
                                );
                              },
                            ),
                          ),
                      ],
                    ),
                  ),
                ),
              ),
            ),
          ],
        ),
      ),
    );

    Overlay.of(context).insert(overlayEntry);
    isOpen.value = true;
  }

  void removeOverlay() {
    isOpen.value = false;
  }

  @override
  void onClose() {
    searchController.dispose();
    super.onClose();
  }
}
