import 'package:auto_route/auto_route.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:gap/gap.dart';
import 'package:krow/core/application/routing/routes.gr.dart';
import 'package:krow/core/data/models/event/event_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 CreateEventPopup extends StatefulWidget {
  const CreateEventPopup({
    super.key,
    required this.child,
    required this.controller,
    required this.opacity,
  });

  final Widget child;
  final ListenableOverlayPortalController controller;

  final double opacity;

  @override
  State<CreateEventPopup> createState() => _CreateEventPopupState();
}

class _CreateEventPopupState extends State<CreateEventPopup> {
  late final ListenableOverlayPortalController _controller;

  @override
  void initState() {
    _controller = widget.controller;

    _controller.addListener(() {
      try {
        if (context.mounted) {
          setState(() {});
        }
      } catch (e) {
        print(e);
      }
    });
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return OverlayPortal(
      controller: _controller,
      overlayChildBuilder: (context) {
        return AnimatedOpacity(
          duration: const Duration(milliseconds: 200),
          opacity: widget.opacity,
          child: AnimatedScale(
            duration: const Duration(milliseconds: 200),
            scale: 0.1 + 0.9 * widget.opacity,
            alignment: const Alignment(0, 0.8),
            child: GestureDetector(
                onTap: () {
                  _controller.hide();
                },
                child: Align(
                  alignment: Alignment.bottomCenter,
                  child: Padding(
                    padding: const EdgeInsets.only(bottom: 125),
                    child: Row(
                      mainAxisSize: MainAxisSize.min,
                      children: [
                        Column(
                          mainAxisSize: MainAxisSize.min,
                          children: [
                            // _buildItem('Create Recurrent Event', () {
                            //   context.router.push(CreateEventFlowRoute(
                            //       children: [
                            //         CreateEventRoute(
                            //             eventType: EventScheduleType.recurring)
                            //       ]));
                            // }),
                            // const Gap(8),
                            _buildItem('Create Event', () {
                              context.router.push(CreateEventFlowRoute(
                                  children: [
                                    CreateEventRoute(
                                        eventType: EventScheduleType.oneTime)
                                  ]));
                            }),
                            const Gap(6),
                            Assets.images.icons.navigation.menuArrow.svg(),
                          ],
                        ),
                      ],
                    ),
                  ),
                )),
          ),
        );
      },
      child: widget.child,
    );
  }

  Widget _buildItem(String title, VoidCallback onTap) {
    return GestureDetector(
      onTap: () {
        onTap();
        _controller.hide();
      },
      child: Container(
        width: 215,
        alignment: Alignment.center,
        decoration: BoxDecoration(
          color: AppColors.buttonPrimaryYellowDrop,
          borderRadius: BorderRadius.circular(24),
        ),
        padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 12),
        child: Text(
          title,
          style: AppTextStyles.bodyMediumMed,
        ),
      ),
    );
  }

  @override
  void dispose() {
    if (context.mounted) _controller.hide();
    super.dispose();
  }
}

class ListenableOverlayPortalController extends OverlayPortalController {
  List<VoidCallback> listeners = [];
  Future<void> Function()? onShow;
  Future<void> Function()? onHide;

  ListenableOverlayPortalController();

  addOnShowListener(Future<void> Function() listener) {
    onShow = listener;
  }

  addOnHideListener(Future<void> Function() listener) {
    onHide = listener;
  }

  @override
  void show() async {
    super.show();
    try {
      for (var element in listeners) {
        element();
      }
    } catch (e) {
      if (kDebugMode) {
        print(e);
      }
    }

    if (onShow != null) {
      await onShow!();
    }
  }

  @override
  void hide() async {
    if (onHide != null) {
      await onHide!();
    }
    try {
      super.hide();
    } catch (e) {
      if (kDebugMode) {
        print(e);
      }
    }
    for (var element in listeners) {
      try {
        element();
      } catch (e) {
        if (kDebugMode) {
          print(e);
        }
      }
    }
  }

  void addListener(VoidCallback listener) {
    listeners.add(listener);
  }
}
