import 'package:flutter/material.dart';

class KwLoadingOverlay extends StatefulWidget {
  const KwLoadingOverlay({
    super.key,
    required this.child,
    this.controller,
    this.shouldShowLoading,
  });

  final Widget child;
  final OverlayPortalController? controller;
  final bool? shouldShowLoading;

  @override
  State<KwLoadingOverlay> createState() => _KwLoadingOverlayState();
}

class _KwLoadingOverlayState extends State<KwLoadingOverlay> {
  late final OverlayPortalController _controller;

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

    if (widget.shouldShowLoading ?? false) {
      WidgetsBinding.instance.addPostFrameCallback(
        (_) => _controller.show(),
      );
    }
  }

  @override
  void didUpdateWidget(covariant KwLoadingOverlay oldWidget) {
    super.didUpdateWidget(oldWidget);

    WidgetsBinding.instance.addPostFrameCallback(
      (_) {
        if (widget.shouldShowLoading == null) return;

        if (widget.shouldShowLoading!) {
          _controller.show();
        } else {
          _controller.hide();
        }
      },
    );
  }

  @override
  Widget build(BuildContext context) {
    return OverlayPortal(
      controller: _controller,
      overlayChildBuilder: (context) {
        return const SizedBox(
          height: double.maxFinite,
          width: double.maxFinite,
          child: DecoratedBox(
            decoration: BoxDecoration(
              color: Colors.black38,
            ),
            child: Center(
              child: CircularProgressIndicator(),
            ),
          ),
        );
      },
      child: widget.child,
    );
  }

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