import 'package:auto_route/auto_route.dart';
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:krow/core/application/routing/routes.gr.dart';
import 'package:krow/core/data/enums/state_status.dart';
import 'package:krow/core/presentation/widgets/ui_kit/kw_button.dart';
import 'package:krow/core/presentation/widgets/ui_kit/kw_loading_overlay.dart';
import 'package:krow/features/profile/emergency_contacts/domain/bloc/emergency_contacts_bloc.dart';

class BottomControlButton extends StatefulWidget {
  const BottomControlButton({
    super.key,
    required this.isInEditMode,
    required this.footerActionName,
  });

  final bool isInEditMode;
  final String footerActionName;

  static const _height = 52.0;

  @override
  State<BottomControlButton> createState() => _BottomControlButtonState();
}

class _BottomControlButtonState extends State<BottomControlButton>
    with WidgetsBindingObserver {
  bool isVisible = true;

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

    WidgetsBinding.instance.addObserver(this);
  }

  @override
  void didChangeMetrics() {
    if (View.of(context).viewInsets.bottom > 0 && isVisible) {
      setState(() => isVisible = false);
    } else if (View.of(context).viewInsets.bottom == 0 && !isVisible) {
      setState(() => isVisible = true);
    }
  }

  @override
  Widget build(BuildContext context) {
    return AnimatedOpacity(
      duration: Durations.short2,
      opacity: isVisible ? 1 : 0,
      child: AnimatedSize(
        duration: Durations.short2,
        alignment: Alignment.bottomCenter,
        child: BlocConsumer<EmergencyContactsBloc, EmergencyContactsState>(
          buildWhen: (previous, current) =>
              previous.status != current.status ||
              previous.isFilled != current.isFilled,
          listenWhen: (previous, current) => previous.status != current.status,
          listener: (context, state) {
            if (state.status == StateStatus.success) {
              if (widget.isInEditMode) {
                Navigator.pop(context);
              } else {
                context.router.push(
                  MobilityRoute(isInEditMode: false),
                );
              }
            }
          },
          builder: (context, state) {
            return KwLoadingOverlay(
              shouldShowLoading: state.status == StateStatus.loading,
              child: KwButton.primary(
                label: widget.footerActionName,
                height: BottomControlButton._height,
                disabled: !state.isFilled,
                onPressed: () {
                  context.read<EmergencyContactsBloc>().add(
                        SaveContactsChanges(),
                      );
                },
              ),
            );
          },
        ),
      ),
    );
  }

  @override
  void dispose() {
    WidgetsBinding.instance.removeObserver(this);
    super.dispose();
  }
}
