import 'package:design_system/design_system.dart';
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:staff_authentication/src/presentation/blocs/auth_bloc.dart';
import 'package:staff_authentication/src/presentation/blocs/auth_event.dart';
import 'package:staff_authentication/src/presentation/blocs/auth_state.dart';
import 'phone_input/phone_input_actions.dart';
import 'phone_input/phone_input_form_field.dart';
import 'phone_input/phone_input_header.dart';

/// A widget that displays the phone number entry UI.
class PhoneInput extends StatefulWidget {
  /// Creates a [PhoneInput].
  const PhoneInput({super.key, required this.state, required this.onSendCode});

  /// The current state of the authentication process.
  final AuthState state;

  /// Callback for when the "Send Code" action is triggered.
  final ValueChanged<String> onSendCode;

  @override
  State<PhoneInput> createState() => _PhoneInputState();
}

class _PhoneInputState extends State<PhoneInput> {
  String _currentPhone = '';

  @override
  void initState() {
    super.initState();
    _currentPhone = widget.state.phoneNumber;
  }

  void _handlePhoneChanged(String value) {
    if (!mounted) return;

    _currentPhone = value;
    final AuthBloc bloc = context.read<AuthBloc>();
    if (!bloc.isClosed) {
      bloc.add(AuthPhoneUpdated(value));
    }
  }

  @override
  Widget build(BuildContext context) {
    return Column(
      children: <Widget>[
        Expanded(
          child: SingleChildScrollView(
            padding: const EdgeInsets.symmetric(
              horizontal: UiConstants.space6,
              vertical: UiConstants.space8,
            ),
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: <Widget>[
                const PhoneInputHeader(),
                const SizedBox(height: UiConstants.space8),
                PhoneInputFormField(
                  initialValue: widget.state.phoneNumber,
                  error: widget.state.errorMessage ?? '',
                  onChanged: _handlePhoneChanged,
                ),
              ],
            ),
          ),
        ),
        PhoneInputActions(
          isLoading: widget.state.isLoading,
          onSendCode: () => widget.onSendCode(_currentPhone),
        ),
      ],
    );
  }
}
