import 'package:fis_common/event/event_type.dart';
import 'package:flutter/material.dart';
import 'package:flyinsono/managers/interfaces/remote_maintenance.dart';
import 'package:get/get.dart';

class FloatingTextButtons extends StatefulWidget {
  final Icon icon;
  final List<Widget> buttons;
  final FEventHandler<bool>? cancelExtendButtonsHandler;
  final void Function(bool)? onExpandChange;
  final bool? isExpanded;
  FloatingTextButtons({
    required this.icon,
    required this.buttons,
    this.cancelExtendButtonsHandler,
    this.onExpandChange,
    this.isExpanded,
  });

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

class _FloatingTextButtonsState extends State<FloatingTextButtons> {
  bool _isExpanded = false;
  OverlayEntry? _overlayEntry;
  Offset _tapPosition = Offset.zero;

  @override
  void initState() {
    _isExpanded = widget.isExpanded ?? false;
    widget.cancelExtendButtonsHandler!.addListener(_onTapHandler);
    super.initState();
  }

  @override
  void didUpdateWidget(FloatingTextButtons oldWidget) {
    if (oldWidget.isExpanded != widget.isExpanded) {
      _isExpanded = widget.isExpanded ?? false;
    }
    super.didUpdateWidget(oldWidget);
  }

  void dispose() {
    widget.cancelExtendButtonsHandler!.removeListener(_onTapHandler);
    super.dispose();
  }

  OverlayEntry _buildOverlayEntry() {
    final screenWidth = MediaQuery.of(context).size.width;
    final screenHeight = MediaQuery.of(context).size.height;
    const buttonHeight = 40.0; // Adjust this based on your button height
    const buttonWidth = 100.0; // Adjust this based on your button width
    const verticalPadding = 10.0;
    const horizontalPadding = 10.0;

    double leftPosition = _tapPosition.dx - (buttonWidth / 2);
    double topPosition = _tapPosition.dy + verticalPadding;

    if (_tapPosition.dx < buttonWidth / 2 + horizontalPadding) {
      leftPosition = horizontalPadding;
    } else if (_tapPosition.dx >
        screenWidth - buttonWidth - horizontalPadding) {
      leftPosition = screenWidth - buttonWidth - horizontalPadding;
    }

    if (_tapPosition.dy > screenHeight - 2 * buttonHeight - verticalPadding) {
      topPosition = _tapPosition.dy - buttonHeight - verticalPadding;
    }

    return OverlayEntry(
      builder: (BuildContext context) {
        return Stack(
          children: [
            Positioned.fill(
              child: GestureDetector(
                onTap: _toggleButtons,
                onTapDown: _handleTapDown,
                child: widget.icon,
              ),
            ),
            Positioned(
              left: leftPosition,
              top: topPosition,
              child: Container(
                color: Colors.white,
                child: Column(
                  mainAxisSize: MainAxisSize.min,
                  children: widget.buttons,
                ),
              ),
            ),
          ],
        );
      },
    );
  }

  Future<void> _toggleButtons() async {
    Get.find<IRemoteMaintenanceManager>()
        .onCancelExtendButtons
        .emit(this, false);
    await Future.delayed(Duration(milliseconds: 100));
    if (_isExpanded) {
      _overlayEntry?.remove();
    } else {
      _overlayEntry = _buildOverlayEntry();
      Overlay.of(context).insert(_overlayEntry!);
    }

    setState(() {
      _isExpanded = !_isExpanded;
    });
    widget.onExpandChange?.call(_isExpanded);
  }

  void _handleTapDown(TapDownDetails details) {
    _tapPosition = details.globalPosition;
  }

  @override
  Widget build(BuildContext context) {
    return GestureDetector(
      onTap: _toggleButtons,
      onTapDown: _handleTapDown,
      child: widget.icon,
    );
  }

  void _onTapHandler(Object sender, bool e) {
    if (_isExpanded) {
      _overlayEntry?.remove();
    }
    setState(() {
      _isExpanded = false;
    });
  }
}
