import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:rasadyar_core/core.dart';

class ResourceOverlayDropdown<T> extends StatefulWidget {
  final Resource<List<T>> items;
  final T? selectedItem;
  final T? initialValue;
  final int? height;
  final Color? background;
  final bool? hasDropIcon;
  final Widget Function(T item) itemBuilder;
  final Widget Function(T? selected) labelBuilder;
  final void Function(T selected)? onChanged;
  final EdgeInsets? contentPadding;
  final bool isDisabled;

  const ResourceOverlayDropdown({
    super.key,
    required this.items,
    required this.itemBuilder,
    required this.labelBuilder,
    this.initialValue,
    this.onChanged,
    this.selectedItem,
    this.contentPadding,
    this.height,
    this.background,
    this.hasDropIcon = true,
    this.isDisabled = false,
  });

  @override
  State<ResourceOverlayDropdown<T>> createState() => _ResourceOverlayDropdownState<T>();
}

class _ResourceOverlayDropdownState<T> extends State<ResourceOverlayDropdown<T>> {
  final GlobalKey _key = GlobalKey();
  OverlayEntry? _overlayEntry;
  bool _isOpen = false;
  T? selectedItem;

  @override
  void initState() {
    super.initState();
    selectedItem = widget.selectedItem ?? widget.initialValue;
  }

  @override
  void didUpdateWidget(covariant ResourceOverlayDropdown<T> oldWidget) {
    super.didUpdateWidget(oldWidget);
    if (widget.selectedItem != oldWidget.selectedItem) {
      setState(() {
        selectedItem = widget.selectedItem;
      });
    }
  }

  void _showOverlay() {
    if (_overlayEntry != null) return;

    final renderBox = _key.currentContext!.findRenderObject() as RenderBox;
    final size = renderBox.size;
    final offset = renderBox.localToGlobal(Offset.zero);

    _overlayEntry = OverlayEntry(
      builder: (_) => GestureDetector(
        onTap: _removeOverlay,
        behavior: HitTestBehavior.translucent,
        child: Stack(
          children: [
            Positioned(
              left: offset.dx,
              top: offset.dy + size.height + 4,
              width: size.width,
              child: Material(
                elevation: 4,
                borderRadius: BorderRadius.circular(8),
                child: Container(
                  decoration: BoxDecoration(
                    color: widget.background ?? AppColor.bgLight,
                    border: Border.all(color: AppColor.darkGreyLight),
                    borderRadius: BorderRadius.circular(8),
                  ),
                  constraints: const BoxConstraints(maxHeight: 300),
                  child: ListView(
                    padding: EdgeInsets.zero,
                    shrinkWrap: true,
                    physics: const BouncingScrollPhysics(),
                    children:
                        widget.items.data?.map((item) {
                          return InkWell(
                            onTap: () {
                              widget.onChanged?.call(item);
                              setState(() {
                                selectedItem = item;
                              });
                              _removeOverlay();
                            },
                            child: Padding(
                              padding:
                                  widget.contentPadding ??
                                  const EdgeInsets.symmetric(horizontal: 8, vertical: 4),
                              child: widget.itemBuilder(item),
                            ),
                          );
                        }).toList() ??
                        [],
                  ),
                ),
              ),
            ),
          ],
        ),
      ),
    );

    Overlay.of(context).insert(_overlayEntry!);
    setState(() => _isOpen = true);
  }

  void _removeOverlay({bool fromDispose = false}) {
    _overlayEntry?.remove();
    _overlayEntry = null;
    if (!fromDispose && mounted) {
      setState(() => _isOpen = false);
    }
  }

  @override
  void dispose() {
    _removeOverlay(fromDispose: true);
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return LayoutBuilder(
      builder: (context, constraints) {
        return GestureDetector(
          key: _key,
          onTap: (widget.isDisabled || widget.items.status == ResourceStatus.loading)
              ? null
              : () {
                  _isOpen ? _removeOverlay() : _showOverlay();
                },
          child: Container(
            height: widget.height?.toDouble() ?? 40,
            width: constraints.maxWidth,
            padding: const EdgeInsets.symmetric(horizontal: 12),
            decoration: BoxDecoration(
              color: widget.background ?? AppColor.bgLight,
              border: Border.all(color: AppColor.darkGreyLight),
              borderRadius: BorderRadius.circular(8),
            ),
            child: _buildWidget(widget.items),
          ),
        );
      },
    );
  }

  Widget? _buildWidget(Resource<List<T>> items) {
    switch (items.status) {
      case ResourceStatus.initial:
      case ResourceStatus.loading:
        return CupertinoActivityIndicator();
      case ResourceStatus.success:
        return Row(
          mainAxisAlignment: MainAxisAlignment.spaceBetween,
          children: [
            Expanded(child: widget.labelBuilder(selectedItem)),
            if (widget.hasDropIcon ?? true)
              Icon(_isOpen ? CupertinoIcons.chevron_up : CupertinoIcons.chevron_down, size: 14),
          ],
        );
      case ResourceStatus.error:
        return Text('Error', style: AppFonts.yekan12.copyWith(color: AppColor.redNormal));

      case ResourceStatus.empty:
        return Text('بدون نتیجه', style: AppFonts.yekan12.copyWith(color: AppColor.textColor));
    }
  }
}
