import 'dart:math';

import 'package:flutter/material.dart';
import 'package:gap/gap.dart';
import 'package:krow/core/data/models/event/business_member_model.dart';
import 'package:krow/core/presentation/gen/assets.gen.dart';
import 'package:krow/core/presentation/styles/kw_text_styles.dart';
import 'package:krow/core/presentation/styles/theme.dart';

class SelectContactPopup extends StatefulWidget {
  final List<BusinessMemberModel> contacts;
  final void Function(BusinessMemberModel contact)? onSelect;
  final Widget child;

  const SelectContactPopup(
      {super.key,
      required this.contacts,
      required this.onSelect,
      required this.child});

  @override
  _SelectContactPopupState createState() => _SelectContactPopupState();
}

class _SelectContactPopupState extends State<SelectContactPopup> {
  OverlayEntry? _overlayEntry;
  List<BusinessMemberModel> _filteredItems = [];
  final ScrollController _scrollController = ScrollController();
  final TextEditingController _controller = TextEditingController();
  final GlobalKey _childKey = GlobalKey();
  double? childY;

  StateSetter? overlaySetState;

  @override
  initState() {
    super.initState();
  }

  void _showPopup(BuildContext context) {
    _filteredItems = List.from(widget.contacts);

    _overlayEntry = OverlayEntry(
      builder: (context) {
        return StatefulBuilder(builder: (context, setState) {
          overlaySetState = setState;
          return Stack(
            children: [
              GestureDetector(
                onTap: _hidePopup,
                behavior: HitTestBehavior.opaque,
                child: Container(color: Colors.transparent),
              ),
              if (childY != null)
                Positioned(
                  height:
                      min(320, 82 + (44 * _filteredItems.length).toDouble()),
                  top: childY,
                  left: 28,
                  right: 28,
                  child: Material(
                    elevation: 4,
                    borderRadius: BorderRadius.circular(10),
                    child: _buildPopupContent(),
                  ),
                ),
            ],
          );
        });
      },
    );

    Overlay.of(context).insert(_overlayEntry!);
  }

  Widget _buildPopupContent() {
    return Container(
      decoration: BoxDecoration(
        border: Border.all(color: AppColors.grayTintStroke),
      ),
      padding: const EdgeInsets.all(12),
      child: Column(
        mainAxisSize: MainAxisSize.min,
        children: [
          Container(
            height: 40,
            padding: const EdgeInsets.symmetric(horizontal: 8),
            decoration: BoxDecoration(
              color: AppColors.grayPrimaryFrame,
              borderRadius: BorderRadius.circular(8),
            ),
            child: Row(
              crossAxisAlignment: CrossAxisAlignment.center,
              children: [
                Assets.images.icons.magnifyingGlass.svg(),
                const Gap(8),
                Expanded(
                  child: TextField(
                    controller: _controller,
                    style: AppTextStyles.bodyLargeMed,
                    decoration: const InputDecoration(
                      contentPadding: EdgeInsets.only(bottom: 8),
                      hintText: 'Search',
                      hintStyle: AppTextStyles.bodyLargeMed,
                      border: InputBorder.none,
                    ),
                    onChanged: _filterItems,
                  ),
                ),
              ],
            ),
          ),
          const SizedBox(height: 16),
          SizedBox(
            height: min(238, (44 * _filteredItems.length).toDouble()),
            child: RawScrollbar(
              controller: _scrollController,
              thumbVisibility: true,
              padding: const EdgeInsets.only(right: 4),
              thumbColor: AppColors.grayDisable,
              trackColor: AppColors.buttonTertiaryActive,
              trackVisibility: true,
              radius: const Radius.circular(20),
              thickness: 4,
              child: ListView.builder(
                controller: _scrollController,
                itemCount: _filteredItems.length,
                shrinkWrap: true,
                padding: EdgeInsets.zero,
                itemBuilder: (context, index) {
                  var item = _filteredItems[index];
                  return GestureDetector(
                    onTap: () {
                      widget.onSelect?.call(item);
                      _hidePopup();
                    },
                    child: Container(
                      padding: const EdgeInsets.all(8),
                      margin: const EdgeInsets.only(bottom: 4),
                      child: Row(
                        children: [
                          Container(
                            width: 24,
                            height: 24,
                            decoration: BoxDecoration(
                              borderRadius: BorderRadius.circular(12),
                              color: Colors.grey,
                            ),
                          ),
                          const Gap(8),
                          Text(
                            '${item.firstName} ${item.lastName}',
                            style: AppTextStyles.bodyMediumMed,
                          ),
                          const Gap(8),
                          Text(
                            item.authInfo?.phone ?? '',
                            style: AppTextStyles.bodySmallMed
                                .copyWith(color: AppColors.blackGray),
                          ),
                        ],
                      ),
                    ),
                  );
                },
              ),
            ),
          ),
        ],
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    return GestureDetector(
        onTap: () {
          final RenderBox renderBox =
              _childKey.currentContext!.findRenderObject() as RenderBox;
          final position = renderBox.localToGlobal(Offset.zero);
          childY = position.dy;
          _showPopup(context);
        },
        key: _childKey,
        child: widget.child);
  }

  void _hidePopup() {
    _overlayEntry?.remove();
    _overlayEntry = null;
    _filteredItems = List.from(widget.contacts);
    _controller.clear();
  }

  void _filterItems(String query) {
    overlaySetState?.call(() {
      _filteredItems = widget.contacts.where((item) {
        return ('${item.firstName}${item.lastName}${item.authInfo?.phone ?? ''}')
            .toLowerCase()
            .contains(query.toLowerCase());
      }).toList();
    });
  }
}
