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) {
          ScaffoldMessenger.of(context).showSnackBar(
            SnackBar(
              content: Text(
                'Emergency contacts saved successfully',
                style: UiTypography.body2r.textPrimary,
              ),
              backgroundColor: UiColors.iconSuccess,
            ),
          );
        }
      },
      builder: (context, state) {
        final isLoading = state.status == EmergencyContactStatus.saving;
        return Container(
          padding: EdgeInsets.all(UiConstants.space4),
          decoration: 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
                  ? SizedBox(
                      height: 20.0,
                      width: 20.0,
                      child: CircularProgressIndicator(
                        strokeWidth: 2,
                        valueColor: AlwaysStoppedAnimation<Color>(
                          UiColors.primaryForeground,
                        ),
                      ),
                    )
                  : const Text('Save & Continue'),
            ),
          ),
        );
      },
    );
  }
}
