import 'package:design_system/design_system.dart';
import 'package:flutter/material.dart';
import 'package:flutter_modular/flutter_modular.dart' hide ModularWatchExtension;
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:krow_domain/krow_domain.dart';

import '../blocs/i9/form_i9_cubit.dart';
import '../blocs/i9/form_i9_state.dart';

class FormI9Page extends StatefulWidget {
  final TaxForm? form;
  const FormI9Page({super.key, this.form});

  @override
  State<FormI9Page> createState() => _FormI9PageState();
}

class _FormI9PageState extends State<FormI9Page> {
  final List<String> _usStates = <String>[
    'AL', 'AK', 'AZ', 'AR', 'CA', 'CO', 'CT', 'DE', 'FL', 'GA',
    'HI', 'ID', 'IL', 'IN', 'IA', 'KS', 'KY', 'LA', 'ME', 'MD',
    'MA', 'MI', 'MN', 'MS', 'MO', 'MT', 'NE', 'NV', 'NH', 'NJ',
    'NM', 'NY', 'NC', 'ND', 'OH', 'OK', 'OR', 'PA', 'RI', 'SC',
    'SD', 'TN', 'TX', 'UT', 'VT', 'VA', 'WA', 'WV', 'WI', 'WY'
  ];

  @override
  void initState() {
    super.initState();
    if (widget.form != null) {
      // Use post-frame callback or simple direct call since we are using Modular.get in build
      // But better helper:
      Modular.get<FormI9Cubit>().initialize(widget.form);
    }
  }

  final List<Map<String, String>> _steps = <Map<String, String>>[
    <String, String>{'title': 'Personal Information', 'subtitle': 'Name and contact details'},
    <String, String>{'title': 'Address', 'subtitle': 'Your current address'},
    <String, String>{'title': 'Citizenship Status', 'subtitle': 'Work authorization verification'},
    <String, String>{'title': 'Review & Sign', 'subtitle': 'Confirm your information'},
  ];

  bool _canProceed(FormI9State state) {
    switch (state.currentStep) {
      case 0:
        return state.firstName.trim().isNotEmpty &&
            state.lastName.trim().isNotEmpty &&
            state.dob.isNotEmpty &&
            state.ssn.replaceAll(RegExp(r'\D'), '').length >= 9;
      case 1:
        return state.address.trim().isNotEmpty &&
            state.city.trim().isNotEmpty &&
            state.state.isNotEmpty &&
            state.zipCode.isNotEmpty;
      case 2:
        return state.citizenshipStatus.isNotEmpty;
      case 3:
        return state.signature.trim().isNotEmpty;
      default:
        return true;
    }
  }

  void _handleNext(BuildContext context, int currentStep) {
    if (currentStep < _steps.length - 1) {
      context.read<FormI9Cubit>().nextStep(_steps.length);
    } else {
      context.read<FormI9Cubit>().submit();
    }
  }

  void _handleBack(BuildContext context) {
    context.read<FormI9Cubit>().previousStep();
  }

  @override
  Widget build(BuildContext context) {
    return BlocProvider<FormI9Cubit>.value(
      value: Modular.get<FormI9Cubit>(),
      child: BlocConsumer<FormI9Cubit, FormI9State>(
        listener: (BuildContext context, FormI9State state) {
          if (state.status == FormI9Status.success) {
            // Success view is handled by state check in build or we can navigate
          } else if (state.status == FormI9Status.failure) {
            final ScaffoldMessengerState messenger = ScaffoldMessenger.of(context);
            messenger.hideCurrentSnackBar();
            messenger.showSnackBar(
              SnackBar(content: Text(state.errorMessage ?? 'An error occurred')),
            );
          }
        },
        builder: (BuildContext context, FormI9State state) {
          if (state.status == FormI9Status.success) return _buildSuccessView();

          return Scaffold(
            backgroundColor: UiColors.background,
            body: Column(
              children: <Widget>[
                _buildHeader(context, state),
                Expanded(
                  child: SingleChildScrollView(
                    padding: const EdgeInsets.symmetric(horizontal: 20, vertical: 24),
                    child: _buildCurrentStep(context, state),
                  ),
                ),
                _buildFooter(context, state),
              ],
            ),
          );
        },
      ),
    );
  }

  Widget _buildSuccessView() {
    return Scaffold(
      backgroundColor: UiColors.background,
      body: Center(
        child: Padding(
          padding: const EdgeInsets.all(24.0),
          child: Container(
            padding: const EdgeInsets.all(32),
            decoration: BoxDecoration(
              color: UiColors.bgPopup,
              borderRadius: BorderRadius.circular(24),
              border: Border.all(color: UiColors.border),
            ),
            child: Column(
              mainAxisSize: MainAxisSize.min,
              children: <Widget>[
                Container(
                  width: 64,
                  height: 64,
                  decoration: const BoxDecoration(
                    color: Color(0xFFDCFCE7),
                    shape: BoxShape.circle,
                  ),
                  child: const Icon(
                    UiIcons.success,
                    color: Color(0xFF16A34A),
                    size: 32,
                  ),
                ),
                const SizedBox(height: 16),
                Text(
                  'Form I-9 Submitted!',
                  style: UiTypography.headline4m.copyWith(
                    color: UiColors.textPrimary,
                  ),
                ),
                const SizedBox(height: 8),
                Text(
                  'Your employment eligibility verification has been submitted.',
                  textAlign: TextAlign.center,
                  style: UiTypography.body2r.copyWith(color: UiColors.textSecondary),
                ),
                const SizedBox(height: 24),
                SizedBox(
                  width: double.infinity,
                  child: ElevatedButton(
                    onPressed: () => Modular.to.pop(),
                    style: ElevatedButton.styleFrom(
                      backgroundColor: UiColors.primary,
                      foregroundColor: UiColors.bgPopup,
                      padding: const EdgeInsets.symmetric(vertical: 16),
                      shape: RoundedRectangleBorder(
                        borderRadius: BorderRadius.circular(12),
                      ),
                      elevation: 0,
                    ),
                    child: const Text('Back to Documents'),
                  ),
                ),
              ],
            ),
          ),
        ),
      ),
    );
  }

  Widget _buildHeader(BuildContext context, FormI9State state) {
    return Container(
      color: UiColors.primary,
      padding: const EdgeInsets.only(top: 60, bottom: 24, left: 20, right: 20),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: <Widget>[
          Row(
            children: <Widget>[
              GestureDetector(
                onTap: () => Modular.to.pop(),
                child: const Icon(
                  UiIcons.arrowLeft,
                  color: UiColors.bgPopup,
                  size: 24,
                ),
              ),
              const SizedBox(width: 12),
              Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: <Widget>[
                  Text(
                    'Form I-9',
                    style: UiTypography.headline4m.copyWith(
                      color: UiColors.bgPopup,
                    ),
                  ),
                  Text(
                    'Employment Eligibility Verification',
                    style: UiTypography.body3r.copyWith(color: UiColors.bgPopup.withOpacity(0.7)),
                  ),
                ],
              ),
            ],
          ),
          const SizedBox(height: 24),
          Row(
            children: _steps.asMap().entries.map((MapEntry<int, Map<String, String>> entry) {
              final int idx = entry.key;
              final bool isLast = idx == _steps.length - 1;
              return Expanded(
                child: Row(
                  children: <Widget>[
                    Expanded(
                      child: Container(
                        height: 4,
                        decoration: BoxDecoration(
                          color: idx <= state.currentStep
                              ? UiColors.bgPopup
                              : UiColors.bgPopup.withOpacity(0.3),
                          borderRadius: BorderRadius.circular(2),
                        ),
                      ),
                    ),
                    if (!isLast) const SizedBox(width: 4),
                  ],
                ),
              );
            }).toList(),
          ),
          const SizedBox(height: 8),
          Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: <Widget>[
              Text(
                'Step ${state.currentStep + 1} of ${_steps.length}',
                style: UiTypography.body3r.copyWith(color: UiColors.bgPopup.withOpacity(0.7)),
              ),
              Expanded(
                child: Text(
                  _steps[state.currentStep]['title']!,
                  textAlign: TextAlign.end,
                  style: UiTypography.body3m.copyWith(
                    color: UiColors.bgPopup,
                    fontWeight: FontWeight.w500,
                  ),
                ),
              ),
            ],
          ),
        ],
      ),
    );
  }

  Widget _buildCurrentStep(BuildContext context, FormI9State state) {
    switch (state.currentStep) {
      case 0:
        return _buildStep1(context, state);
      case 1:
        return _buildStep2(context, state);
      case 2:
        return _buildStep3(context, state);
      case 3:
        return _buildStep4(context, state);
      default:
        return Container();
    }
  }

  Widget _buildTextField(
    String label, {
    required String value,
    required ValueChanged<String> onChanged,
    TextInputType? keyboardType,
    String? placeholder,
  }) {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: <Widget>[
        Text(
          label,
          style: UiTypography.body3m.copyWith(
            color: UiColors.textSecondary,
            fontWeight: FontWeight.w500,
          ),
        ),
        const SizedBox(height: 6),
        TextField(
          controller: TextEditingController(text: value)
            ..selection = TextSelection.fromPosition(
              TextPosition(offset: value.length),
            ),
          onChanged: onChanged,
          keyboardType: keyboardType,
          style: UiTypography.body2r.copyWith(color: UiColors.textPrimary),
          decoration: InputDecoration(
            hintText: placeholder,
            hintStyle: TextStyle(color: Colors.grey[400]),
            filled: true,
            fillColor: UiColors.bgPopup,
            contentPadding: const EdgeInsets.symmetric(
              horizontal: 16,
              vertical: 16,
            ),
            border: OutlineInputBorder(
              borderRadius: BorderRadius.circular(12),
              borderSide: const BorderSide(color: UiColors.border),
            ),
            enabledBorder: OutlineInputBorder(
              borderRadius: BorderRadius.circular(12),
              borderSide: const BorderSide(color: UiColors.border),
            ),
            focusedBorder: OutlineInputBorder(
              borderRadius: BorderRadius.circular(12),
              borderSide: const BorderSide(color: UiColors.primary),
            ),
          ),
        ),
      ],
    );
  }

  Widget _buildStep1(BuildContext context, FormI9State state) {
    return Column(
      children: <Widget>[
        Row(
          children: <Widget>[
            Expanded(
              child: _buildTextField(
                'First Name *',
                value: state.firstName,
                onChanged: (String val) => context.read<FormI9Cubit>().firstNameChanged(val),
                placeholder: 'John',
              ),
            ),
            const SizedBox(width: 12),
            Expanded(
              child: _buildTextField(
                'Last Name *',
                value: state.lastName,
                onChanged: (String val) => context.read<FormI9Cubit>().lastNameChanged(val),
                placeholder: 'Smith',
              ),
            ),
          ],
        ),
        const SizedBox(height: 16),
        Row(
          children: <Widget>[
            Expanded(
              child: _buildTextField(
                'Middle Initial',
                value: state.middleInitial,
                onChanged: (String val) => context.read<FormI9Cubit>().middleInitialChanged(val),
                placeholder: 'A',
              ),
            ),
            const SizedBox(width: 12),
            Expanded(
              flex: 2,
              child: _buildTextField(
                'Other Last Names',
                value: state.otherLastNames,
                onChanged: (String val) => context.read<FormI9Cubit>().otherLastNamesChanged(val),
                placeholder: 'Maiden name (if any)',
              ),
            ),
          ],
        ),
        const SizedBox(height: 16),
        _buildTextField(
          'Date of Birth *',
          value: state.dob,
          onChanged: (String val) => context.read<FormI9Cubit>().dobChanged(val),
          placeholder: 'MM/DD/YYYY',
          keyboardType: TextInputType.datetime,
        ),
        const SizedBox(height: 16),
        _buildTextField(
          'Social Security Number *',
          value: state.ssn,
          placeholder: 'XXX-XX-XXXX',
          keyboardType: TextInputType.number,
          onChanged: (String val) {
            String text = val.replaceAll(RegExp(r'\D'), '');
            if (text.length > 9) text = text.substring(0, 9);
            context.read<FormI9Cubit>().ssnChanged(text);
          },
        ),
        const SizedBox(height: 16),
        _buildTextField(
          'Email Address',
          value: state.email,
          onChanged: (String val) => context.read<FormI9Cubit>().emailChanged(val),
          keyboardType: TextInputType.emailAddress,
          placeholder: 'john.smith@example.com',
        ),
        const SizedBox(height: 16),
        _buildTextField(
          'Phone Number',
          value: state.phone,
          onChanged: (String val) => context.read<FormI9Cubit>().phoneChanged(val),
          keyboardType: TextInputType.phone,
          placeholder: '(555) 555-5555',
        ),
      ],
    );
  }

  Widget _buildStep2(BuildContext context, FormI9State state) {
    return Column(
      children: <Widget>[
        _buildTextField(
          'Address (Street Number and Name) *',
          value: state.address,
          onChanged: (String val) => context.read<FormI9Cubit>().addressChanged(val),
          placeholder: '123 Main Street',
        ),
        const SizedBox(height: 16),
        _buildTextField(
          'Apt. Number',
          value: state.aptNumber,
          onChanged: (String val) => context.read<FormI9Cubit>().aptNumberChanged(val),
          placeholder: '4B',
        ),
        const SizedBox(height: 16),
        Row(
          children: <Widget>[
            Expanded(
              flex: 2,
              child: _buildTextField(
                'City or Town *',
                value: state.city,
                onChanged: (String val) => context.read<FormI9Cubit>().cityChanged(val),
                placeholder: 'San Francisco',
              ),
            ),
            const SizedBox(width: 12),
            Expanded(
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: <Widget>[
                  Text(
                    'State *',
                    style: UiTypography.body3m.copyWith(
                      color: UiColors.textSecondary,
                      fontWeight: FontWeight.w500,
                    ),
                  ),
                  const SizedBox(height: 6),
                  DropdownButtonFormField<String>(
                    value: state.state.isEmpty ? null : state.state,
                    onChanged: (String? val) => context.read<FormI9Cubit>().stateChanged(val ?? ''),
                    items: _usStates.map((String stateAbbr) {
                      return DropdownMenuItem<String>(
                        value: stateAbbr,
                        child: Text(stateAbbr),
                      );
                    }).toList(),
                    decoration: InputDecoration(
                      filled: true,
                      fillColor: UiColors.bgPopup,
                      contentPadding: const EdgeInsets.symmetric(horizontal: 16),
                      border: OutlineInputBorder(
                        borderRadius: BorderRadius.circular(12),
                        borderSide: const BorderSide(color: UiColors.border),
                      ),
                      enabledBorder: OutlineInputBorder(
                        borderRadius: BorderRadius.circular(12),
                        borderSide: const BorderSide(color: UiColors.border),
                      ),
                    ),
                  ),
                ],
              ),
            ),
          ],
        ),
        const SizedBox(height: 16),
        _buildTextField(
          'ZIP Code *',
          value: state.zipCode,
          onChanged: (String val) => context.read<FormI9Cubit>().zipCodeChanged(val),
          placeholder: '94103',
          keyboardType: TextInputType.number,
        ),
      ],
    );
  }

  Widget _buildStep3(BuildContext context, FormI9State state) {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: <Widget>[
        Text(
          'I attest, under penalty of perjury, that I am (check one of the following boxes):',
          style: UiTypography.body2m.copyWith(color: UiColors.textPrimary),
        ),
        const SizedBox(height: 24),
        _buildRadioOption(
          context,
          state,
          'citizen',
          '1. A citizen of the United States',
        ),
        const SizedBox(height: 12),
        _buildRadioOption(
          context,
          state,
          'noncitizen_national',
          '2. A noncitizen national of the United States',
        ),
        const SizedBox(height: 12),
        _buildRadioOption(
          context,
          state,
          'permanent_resident',
          '3. A lawful permanent resident',
          child: state.citizenshipStatus == 'permanent_resident'
              ? Padding(
                  padding: const EdgeInsets.only(top: 12),
                  child: _buildTextField(
                    'USCIS Number',
                    value: state.uscisNumber,
                    onChanged: (String val) => context.read<FormI9Cubit>().uscisNumberChanged(val),
                    placeholder: 'A-123456789',
                  ),
                )
              : null,
        ),
        const SizedBox(height: 12),
        _buildRadioOption(
          context,
          state,
          'alien_authorized',
          '4. An alien authorized to work',
          child: state.citizenshipStatus == 'alien_authorized'
              ? Padding(
                  padding: const EdgeInsets.only(top: 12),
                  child: Column(
                    children: <Widget>[
                      _buildTextField(
                        'USCIS/Admission Number',
                        value: state.admissionNumber,
                        onChanged: (String val) => context.read<FormI9Cubit>().admissionNumberChanged(val),
                      ),
                      const SizedBox(height: 12),
                      _buildTextField(
                        'Foreign Passport Number',
                        value: state.passportNumber,
                        onChanged: (String val) => context.read<FormI9Cubit>().passportNumberChanged(val),
                      ),
                      const SizedBox(height: 12),
                      _buildTextField(
                        'Country of Issuance',
                        value: state.countryIssuance,
                        onChanged: (String val) => context.read<FormI9Cubit>().countryIssuanceChanged(val),
                      ),
                    ],
                  ),
                )
              : null,
        ),
      ],
    );
  }

  Widget _buildRadioOption(BuildContext context, FormI9State state, String value, String label, {Widget? child}) {
    final bool isSelected = state.citizenshipStatus == value;
    return GestureDetector(
      onTap: () => context.read<FormI9Cubit>().citizenshipStatusChanged(value),
      child: Container(
        padding: const EdgeInsets.all(16),
        decoration: BoxDecoration(
          color: UiColors.bgPopup,
          borderRadius: BorderRadius.circular(12),
          border: Border.all(
            color: isSelected ? UiColors.primary : UiColors.border,
            width: isSelected ? 2 : 1,
          ),
        ),
        child: Column(
          children: <Widget>[
            Row(
              children: <Widget>[
                Container(
                  width: 20,
                  height: 20,
                  decoration: BoxDecoration(
                    shape: BoxShape.circle,
                    border: Border.all(
                      color: isSelected ? UiColors.primary : Colors.grey,
                      width: isSelected ? 6 : 2,
                    ),
                  ),
                ),
                const SizedBox(width: 12),
                Expanded(
                  child: Text(
                    label,
                    style: UiTypography.body2m.copyWith(
                      color: UiColors.textPrimary,
                    ),
                  ),
                ),
              ],
            ),
            if (child != null) child,
          ],
        ),
      ),
    );
  }

  Widget _buildStep4(BuildContext context, FormI9State state) {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: <Widget>[
        Container(
          padding: const EdgeInsets.all(16),
          decoration: BoxDecoration(
            color: UiColors.bgPopup,
            borderRadius: BorderRadius.circular(12),
            border: Border.all(color: UiColors.border),
          ),
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: <Widget>[
              Text(
                'Summary',
                style: UiTypography.headline4m.copyWith(fontSize: 14),
              ),
              const SizedBox(height: 12),
              _buildSummaryRow('Name', '${state.firstName} ${state.lastName}'),
              _buildSummaryRow('Address', '${state.address}, ${state.city}'),
              _buildSummaryRow('SSN', '***-**-${state.ssn.length >= 4 ? state.ssn.substring(state.ssn.length - 4) : '****'}'),
              _buildSummaryRow('Citizenship', _getReadableCitizenship(state.citizenshipStatus)),
            ],
          ),
        ),
        const SizedBox(height: 24),
        CheckboxListTile(
          value: state.preparerUsed,
          onChanged: (bool? val) {
            context.read<FormI9Cubit>().preparerUsedChanged(val ?? false);
          },
          contentPadding: EdgeInsets.zero,
          title: Text(
            'I used a preparer or translator',
            style: UiTypography.body2r.copyWith(color: UiColors.textPrimary),
          ),
          controlAffinity: ListTileControlAffinity.leading,
          activeColor: UiColors.primary,
        ),
        const SizedBox(height: 24),
        Container(
          padding: const EdgeInsets.all(16),
          decoration: BoxDecoration(
            color: Colors.amber[50],
            borderRadius: BorderRadius.circular(12),
          ),
          child: const Text(
            'I am aware that federal law provides for imprisonment and/or fines for false statements or use of false documents in connection with the completion of this form.',
            style: TextStyle(fontSize: 12, color: Color(0xFFB45309)),
          ),
        ),
        const SizedBox(height: 24),
        Text(
          'Signature (type your full name) *',
          style: UiTypography.body3m.copyWith(
            color: UiColors.textSecondary,
          ),
        ),
        const SizedBox(height: 6),
        TextField(
          controller: TextEditingController(text: state.signature)
            ..selection = TextSelection.fromPosition(
              TextPosition(offset: state.signature.length),
            ),
          onChanged: (String val) => context.read<FormI9Cubit>().signatureChanged(val),
          decoration: InputDecoration(
            hintText: 'Type your full name',
            filled: true,
            fillColor: UiColors.bgPopup,
            contentPadding: const EdgeInsets.symmetric(
              horizontal: 16,
              vertical: 16,
            ),
            border: OutlineInputBorder(
              borderRadius: BorderRadius.circular(12),
              borderSide: const BorderSide(color: UiColors.border),
            ),
            enabledBorder: OutlineInputBorder(
              borderRadius: BorderRadius.circular(12),
              borderSide: const BorderSide(color: UiColors.border),
            ),
            focusedBorder: OutlineInputBorder(
              borderRadius: BorderRadius.circular(12),
              borderSide: const BorderSide(color: UiColors.primary),
            ),
          ),
          style: const TextStyle(fontFamily: 'Cursive', fontSize: 18),
        ),
        const SizedBox(height: 16),
         Text(
          'Date',
          style: UiTypography.body3m.copyWith(
            color: UiColors.textSecondary,
          ),
        ),
        const SizedBox(height: 6),
        Container(
          width: double.infinity,
          padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 16),
          decoration: BoxDecoration(
            color: const Color(0xFFF3F4F6),
            borderRadius: BorderRadius.circular(12),
            border: Border.all(color: UiColors.border),
          ),
          child: Text(
            DateTime.now().toString().split(' ')[0],
            style: const TextStyle(color: UiColors.textPrimary),
          ),
        ),
      ],
    );
  }

  Widget _buildSummaryRow(String label, String value) {
    return Padding(
      padding: const EdgeInsets.only(bottom: 8),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        children: <Widget>[
          Text(
            label,
            style: UiTypography.body2r.copyWith(color: UiColors.textSecondary),
          ),
          Expanded(
            child: Text(
              value,
              textAlign: TextAlign.end,
              style: UiTypography.body2m.copyWith(
                color: UiColors.textPrimary,
              ),
            ),
          ),
        ],
      ),
    );
  }

  String _getReadableCitizenship(String status) {
    switch (status) {
      case 'citizen':
        return 'US Citizen';
      case 'noncitizen_national':
        return 'Noncitizen National';
      case 'permanent_resident':
        return 'Permanent Resident';
      case 'alien_authorized':
        return 'Alien Authorized to Work';
      default:
        return 'Unknown';
    }
  }

  Widget _buildFooter(BuildContext context, FormI9State state) {
    return Container(
      padding: const EdgeInsets.all(16),
      decoration: const BoxDecoration(
        color: UiColors.bgPopup,
        border: Border(top: BorderSide(color: UiColors.border)),
      ),
      child: SafeArea(
        child: Row(
          children: <Widget>[
            if (state.currentStep > 0)
              Expanded(
                child: Padding(
                  padding: const EdgeInsets.only(right: 12),
                  child: OutlinedButton(
                    onPressed: () => _handleBack(context),
                    style: OutlinedButton.styleFrom(
                      padding: const EdgeInsets.symmetric(vertical: 16),
                      side: const BorderSide(color: UiColors.border),
                      shape: RoundedRectangleBorder(
                        borderRadius: BorderRadius.circular(12),
                      ),
                    ),
                    child: Row(
                      mainAxisAlignment: MainAxisAlignment.center,
                      children: <Widget>[
                        const Icon(UiIcons.arrowLeft, size: 16, color: UiColors.textPrimary),
                        const SizedBox(width: 8),
                        Text(
                          'Back',
                          style: UiTypography.body2r.copyWith(color: UiColors.textPrimary),
                        ),
                      ],
                    ),
                  ),
                ),
              ),
            Expanded(
              flex: 2,
              child: ElevatedButton(
                onPressed: (_canProceed(state) && state.status != FormI9Status.submitting)
                    ? () => _handleNext(context, state.currentStep)
                    : null,
                style: ElevatedButton.styleFrom(
                  backgroundColor: UiColors.primary,
                  disabledBackgroundColor: Colors.grey[300],
                  foregroundColor: UiColors.bgPopup,
                  padding: const EdgeInsets.symmetric(vertical: 16),
                  shape: RoundedRectangleBorder(
                    borderRadius: BorderRadius.circular(12),
                  ),
                  elevation: 0,
                ),
                child: state.status == FormI9Status.submitting
                    ? const SizedBox(
                        width: 20,
                        height: 20,
                        child: CircularProgressIndicator(
                          color: UiColors.bgPopup,
                          strokeWidth: 2,
                        ),
                      )
                    : Row(
                        mainAxisAlignment: MainAxisAlignment.center,
                        children: <Widget>[
                          Text(
                            state.currentStep == _steps.length - 1
                                ? 'Sign & Submit'
                                : 'Continue',
                          ),
                          if (state.currentStep < _steps.length - 1) ...<Widget>[
                            const SizedBox(width: 8),
                            const Icon(UiIcons.arrowRight, size: 16, color: UiColors.bgPopup),
                          ],
                        ],
                      ),
              ),
            ),
          ],
        ),
      ),
    );
  }
}
