import 'package:core_localization/core_localization.dart';
import 'package:design_system/design_system.dart';
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import '../blocs/emergency_contact_bloc.dart';

class EmergencyContactSaveButton extends StatelessWidget {
  const EmergencyContactSaveButton({super.key});

  void _onSave(BuildContext context) {
    context.read<EmergencyContactBloc>().add(EmergencyContactsSaved());
  }

  @override
  Widget build(BuildContext context) {
    return BlocConsumer<EmergencyContactBloc, EmergencyContactState>(
      listenWhen: (previous, current) => previous.status != current.status,
      listener: (context, state) {
        if (state.status == EmergencyContactStatus.saved) {
          UiSnackbar.show(
            context,
            message: t.staff.profile.menu_items.emergency_contact_page.save_success,
            type: UiSnackbarType.success,
            margin: const EdgeInsets.only(bottom: 150, left: 16, right: 16),
          );
        }
      },
      builder: (context, state) {
        final isLoading = state.status == EmergencyContactStatus.saving;
        return Container(
          padding: const EdgeInsets.all(UiConstants.space4),
          decoration: const BoxDecoration(
            color: UiColors.bgPopup,
            border: Border(top: BorderSide(color: UiColors.border)),
          ),
          child: SafeArea(
            child: UiButton.primary(
              fullWidth: true,
              onPressed:
                  state.isValid && !isLoading ? () => _onSave(context) : null,
              child: isLoading
                  ? const SizedBox(
                      height: 20.0,
                      width: 20.0,
                      child: CircularProgressIndicator(
                        strokeWidth: 2,
                        valueColor: AlwaysStoppedAnimation<Color>(
                          UiColors.primaryForeground,
                        ),
                      ),
                    )
                  : Text(t.staff.profile.menu_items.emergency_contact_page.save_continue),
            ),
          ),
        );
      },
    );
  }
}
