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/w4/form_w4_cubit.dart';
import '../blocs/w4/form_w4_state.dart';

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

  @override
  State<FormW4Page> createState() => _FormW4PageState();
}

class _FormW4PageState extends State<FormW4Page> {
  @override
  void initState() {
    super.initState();
    if (widget.form != null) {
      Modular.get<FormW4Cubit>().initialize(widget.form);
    }
  }

  final List<String> _usStates = <String>[
    'Alabama',
    'Alaska',
    'Arizona',
    'Arkansas',
    'California',
    'Colorado',
    'Connecticut',
    'Delaware',
    'Florida',
    'Georgia',
    'Hawaii',
    'Idaho',
    'Illinois',
    'Indiana',
    'Iowa',
    'Kansas',
    'Kentucky',
    'Louisiana',
    'Maine',
    'Maryland',
    'Massachusetts',
    'Michigan',
    'Minnesota',
    'Mississippi',
    'Missouri',
    'Montana',
    'Nebraska',
    'Nevada',
    'New Hampshire',
    'New Jersey',
    'New Mexico',
    'New York',
    'North Carolina',
    'North Dakota',
    'Ohio',
    'Oklahoma',
    'Oregon',
    'Pennsylvania',
    'Rhode Island',
    'South Carolina',
    'South Dakota',
    'Tennessee',
    'Texas',
    'Utah',
    'Vermont',
    'Virginia',
    'Washington',
    'West Virginia',
    'Wisconsin',
    'Wyoming',
  ];

  final List<Map<String, String>> _steps = <Map<String, String>>[
    <String, String>{'title': 'Personal Information', 'subtitle': 'Step 1'},
    <String, String>{'title': 'Filing Status', 'subtitle': 'Step 1c'},
    <String, String>{'title': 'Multiple Jobs', 'subtitle': 'Step 2 (optional)'},
    <String, String>{'title': 'Dependents', 'subtitle': 'Step 3'},
    <String, String>{'title': 'Other Adjustments', 'subtitle': 'Step 4 (optional)'},
    <String, String>{'title': 'Review & Sign', 'subtitle': 'Step 5'},
  ];

  bool _canProceed(FormW4State state) {
    switch (state.currentStep) {
      case 0:
        return state.firstName.trim().isNotEmpty &&
            state.lastName.trim().isNotEmpty &&
            state.ssn.replaceAll(RegExp(r'\D'), '').length >= 4 &&
            state.address.trim().isNotEmpty;
      case 1:
        return state.filingStatus.isNotEmpty;
      case 5:
        return state.signature.trim().isNotEmpty;
      default:
        return true;
    }
  }

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

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


  int _totalCredits(FormW4State state) {
    return (state.qualifyingChildren * 2000) +
        (state.otherDependents * 500);
  }

  @override
  Widget build(BuildContext context) {
    return BlocProvider<FormW4Cubit>.value(
      value: Modular.get<FormW4Cubit>(),
      child: BlocConsumer<FormW4Cubit, FormW4State>(
        listener: (BuildContext context, FormW4State state) {
          if (state.status == FormW4Status.success) {
            // Handled in builder
          } else if (state.status == FormW4Status.failure) {
             final ScaffoldMessengerState messenger = ScaffoldMessenger.of(context);
            messenger.hideCurrentSnackBar();
            messenger.showSnackBar(
              SnackBar(content: Text(state.errorMessage ?? 'An error occurred')),
            );
          }
        },
        builder: (BuildContext context, FormW4State state) {
          if (state.status == FormW4Status.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 W-4 Submitted!',
                  style: UiTypography.headline4m.copyWith(
                    color: UiColors.textPrimary,
                  ),
                ),
                const SizedBox(height: 8),
                Text(
                  'Your withholding certificate has been submitted to your employer.',
                  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, FormW4State 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 W-4',
                    style: UiTypography.headline4m.copyWith(
                      color: UiColors.bgPopup,
                    ),
                  ),
                  Text(
                    'Employee\'s Withholding Certificate',
                    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)),
              ),
              Text(
                _steps[state.currentStep]['title']!,
                style: UiTypography.body3m.copyWith(
                  color: UiColors.bgPopup,
                  fontWeight: FontWeight.w500,
                ),
              ),
            ],
          ),
        ],
      ),
    );
  }

  Widget _buildCurrentStep(BuildContext context, FormW4State 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);
      case 4:
        return _buildStep5(context, state);
      case 5:
        return _buildStep6(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, FormW4State state) {
    return Column(
      children: <Widget>[
        Row(
          children: <Widget>[
            Expanded(
              child: _buildTextField(
                'First Name *',
                value: state.firstName,
                onChanged: (String val) => context.read<FormW4Cubit>().firstNameChanged(val),
                placeholder: 'John',
              ),
            ),
            const SizedBox(width: 12),
            Expanded(
              child: _buildTextField(
                'Last Name *',
                value: state.lastName,
                onChanged: (String val) => context.read<FormW4Cubit>().lastNameChanged(val),
                placeholder: 'Smith',
              ),
            ),
          ],
        ),
        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<FormW4Cubit>().ssnChanged(text);
          },
        ),
        const SizedBox(height: 16),
        _buildTextField(
          'Address *',
          value: state.address,
          onChanged: (String val) => context.read<FormW4Cubit>().addressChanged(val),
          placeholder: '123 Main Street',
        ),
        const SizedBox(height: 16),
        _buildTextField(
          'City, State, ZIP',
          value: state.cityStateZip,
          onChanged: (String val) => context.read<FormW4Cubit>().cityStateZipChanged(val),
          placeholder: 'San Francisco, CA 94102',
        ),
      ],
    );
  }

  Widget _buildStep2(BuildContext context, FormW4State state) {
    return Column(
      children: <Widget>[
        Container(
          padding: const EdgeInsets.all(16),
          decoration: BoxDecoration(
            color: Colors.blue[50],
            borderRadius: BorderRadius.circular(12),
          ),
          child: Row(
            children: const <Widget>[
              Icon(UiIcons.info, color: Color(0xFF2563EB), size: 20),
              SizedBox(width: 12),
              Expanded(
                child: Text(
                  'Your filing status determines your standard deduction and tax rates.',
                  style: TextStyle(fontSize: 14, color: Color(0xFF1D4ED8)),
                ),
              ),
            ],
          ),
        ),
        const SizedBox(height: 24),
        _buildRadioOption(
          context,
          state,
          'single',
          'Single or Married filing separately',
          null,
        ),
        const SizedBox(height: 12),
        _buildRadioOption(
          context,
          state,
          'married',
          'Married filing jointly or Qualifying surviving spouse',
          null,
        ),
        const SizedBox(height: 12),
        _buildRadioOption(
          context,
          state,
          'head_of_household',
          'Head of household',
          'Check only if you\'re unmarried and pay more than half the costs of keeping up a home',
        ),
      ],
    );
  }

  Widget _buildRadioOption(BuildContext context, FormW4State state, String value, String label, String? subLabel) {
    final bool isSelected = state.filingStatus == value;
    return GestureDetector(
      onTap: () => context.read<FormW4Cubit>().filingStatusChanged(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: Row(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: <Widget>[
            Container(
              margin: const EdgeInsets.only(top: 2),
              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: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: <Widget>[
                  Text(
                    label,
                    style: UiTypography.body2m.copyWith(
                      color: UiColors.textPrimary,
                    ),
                  ),
                  if (subLabel != null) ...<Widget>[
                    const SizedBox(height: 4),
                    Text(
                      subLabel,
                      style: UiTypography.body3r.copyWith(
                        color: UiColors.textSecondary,
                      ),
                    ),
                  ],
                ],
              ),
            ),
          ],
        ),
      ),
    );
  }

  Widget _buildStep3(BuildContext context, FormW4State state) {
    return Column(
      children: <Widget>[
        Container(
          padding: const EdgeInsets.all(16),
          decoration: BoxDecoration(
            color: Colors.amber[50],
            borderRadius: BorderRadius.circular(12),
          ),
          child: const Row(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: <Widget>[
              Icon(
                UiIcons.help,
                color: Color(0xFFD97706),
                size: 20,
              ),
              SizedBox(width: 12),
              Expanded(
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: <Widget>[
                    Text(
                      'When to complete this step?',
                      style: TextStyle(
                        fontWeight: FontWeight.w600,
                        color: Color(0xFF92400E),
                        fontSize: 14,
                      ),
                    ),
                    SizedBox(height: 4),
                    Text(
                      'Complete this step only if you hold more than one job at a time, or are married filing jointly and your spouse also works.',
                      style: TextStyle(fontSize: 12, color: Color(0xFFB45309)),
                    ),
                  ],
                ),
              ),
            ],
          ),
        ),
        const SizedBox(height: 24),
        GestureDetector(
          onTap: () => context.read<FormW4Cubit>().multipleJobsChanged(!state.multipleJobs),
          child: Container(
            padding: const EdgeInsets.all(16),
            decoration: BoxDecoration(
              color: UiColors.bgPopup,
              borderRadius: BorderRadius.circular(12),
              border: Border.all(
                color: state.multipleJobs
                    ? UiColors.primary
                    : UiColors.border,
              ),
            ),
            child: Row(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: <Widget>[
                Container(
                  width: 24,
                  height: 24,
                  decoration: BoxDecoration(
                    color: state.multipleJobs
                        ? UiColors.primary
                        : UiColors.bgPopup,
                    borderRadius: BorderRadius.circular(6),
                    border: Border.all(
                      color: state.multipleJobs
                          ? UiColors.primary
                          : Colors.grey,
                    ),
                  ),
                  child: state.multipleJobs
                      ? const Icon(
                          UiIcons.check,
                          color: UiColors.bgPopup,
                          size: 16,
                        )
                      : null,
                ),
                const SizedBox(width: 12),
                Expanded(
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: <Widget>[
                      Text(
                        'I have multiple jobs or my spouse works',
                        style: UiTypography.body2m.copyWith(
                          color: UiColors.textPrimary,
                        ),
                      ),
                      const SizedBox(height: 4),
                      Text(
                        'Check this box if there are only two jobs total',
                        style: UiTypography.body3r.copyWith(
                          color: UiColors.textSecondary,
                        ),
                      ),
                    ],
                  ),
                ),
              ],
            ),
          ),
        ),
        const SizedBox(height: 16),
        Text(
          'If this does not apply, you can continue to the next step',
          textAlign: TextAlign.center,
          style: UiTypography.body3r.copyWith(color: UiColors.textSecondary),
        ),
      ],
    );
  }

  Widget _buildStep4(BuildContext context, FormW4State state) {
    return Column(
      children: <Widget>[
        Container(
          padding: const EdgeInsets.all(16),
          decoration: BoxDecoration(
            color: Colors.blue[50], // Same note about blue migration
            borderRadius: BorderRadius.circular(12),
          ),
          child: const Row(
            children: <Widget>[
              Icon(UiIcons.info, color: Color(0xFF2563EB), size: 20),
              SizedBox(width: 12),
              Expanded(
                child: Text(
                  'If your total income will be \$200,000 or less (\$400,000 if married filing jointly), you may claim credits for dependents.',
                  style: TextStyle(fontSize: 14, color: Color(0xFF1D4ED8)),
                ),
              ),
            ],
          ),
        ),
        const SizedBox(height: 24),
        Container(
          padding: const EdgeInsets.all(16),
          decoration: BoxDecoration(
            color: UiColors.bgPopup,
            borderRadius: BorderRadius.circular(16),
            border: Border.all(color: UiColors.border),
          ),
          child: Column(
            children: <Widget>[
              _buildCounter(
                context,
                state,
                'Qualifying children under age 17',
                '\$2,000 each',
                (FormW4State s) => s.qualifyingChildren,
                (int val) => context.read<FormW4Cubit>().qualifyingChildrenChanged(val),
              ),
              const Padding(
                padding: EdgeInsets.symmetric(vertical: 16),
                child: Divider(height: 1, color: UiColors.border),
              ),
              _buildCounter(
                context,
                state,
                'Other dependents',
                '\$500 each',
                (FormW4State s) => s.otherDependents,
                (int val) => context.read<FormW4Cubit>().otherDependentsChanged(val),
              ),
            ],
          ),
        ),
        if (_totalCredits(state) > 0) ...<Widget>[
          const SizedBox(height: 16),
          Container(
            padding: const EdgeInsets.all(16),
            decoration: BoxDecoration(
              color: const Color(0xFFDCFCE7),
              borderRadius: BorderRadius.circular(12),
            ),
            child: Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: <Widget>[
                const Text(
                  'Total credits (Step 3)',
                  style: TextStyle(
                    fontWeight: FontWeight.w500,
                    color: Color(0xFF166534),
                  ),
                ),
                Text(
                  '\$${_totalCredits(state)}',
                  style: const TextStyle(
                    fontWeight: FontWeight.bold,
                    fontSize: 18,
                    color: Color(0xFF15803D),
                  ),
                ),
              ],
            ),
          ),
        ],
      ],
    );
  }

  Widget _buildCounter(
    BuildContext context,
    FormW4State state,
    String label,
    String badge,
    int Function(FormW4State) getValue,
    Function(int) onChanged,
  ) {
    final int value = getValue(state);
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: <Widget>[
        Row(
          mainAxisAlignment: MainAxisAlignment.spaceBetween,
          children: <Widget>[
            Expanded(
              child: Text(
                label,
                style: UiTypography.body2m,
              ),
            ),
            Container(
              padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 4),
              decoration: BoxDecoration(
                color: const Color(0xFFDCFCE7),
                borderRadius: BorderRadius.circular(12),
              ),
              child: Text(
                badge,
                style: const TextStyle(
                  fontSize: 10,
                  color: Color(0xFF15803D),
                  fontWeight: FontWeight.bold,
                ),
              ),
            ),
          ],
        ),
        const SizedBox(height: 12),
        Row(
          children: <Widget>[
            _buildCircleBtn(
              UiIcons.minus,
              () => onChanged(value > 0 ? value - 1 : 0),
            ),
            SizedBox(
              width: 48,
              child: Text(
                value.toString(),
                textAlign: TextAlign.center,
                style: const TextStyle(
                  fontSize: 20,
                  fontWeight: FontWeight.bold,
                ),
              ),
            ),
            _buildCircleBtn(
              UiIcons.add,
              () => onChanged(value + 1),
            ),
          ],
        ),
      ],
    );
  }

  Widget _buildCircleBtn(IconData icon, VoidCallback onTap) {
    return GestureDetector(
      onTap: onTap,
      child: Container(
        width: 40,
        height: 40,
        decoration: BoxDecoration(
          shape: BoxShape.circle,
          border: Border.all(color: UiColors.border),
          color: UiColors.bgPopup,
        ),
        child: Icon(icon, size: 20, color: UiColors.textPrimary),
      ),
    );
  }

  Widget _buildStep5(BuildContext context, FormW4State state) {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: <Widget>[
        Text(
          'These adjustments are optional. You can skip them if they don\'t apply.',
          style: UiTypography.body2r.copyWith(color: UiColors.textSecondary),
        ),
        const SizedBox(height: 24),
        _buildTextField(
          '4(a) Other income (not from jobs)',
          value: state.otherIncome,
          onChanged: (String val) => context.read<FormW4Cubit>().otherIncomeChanged(val),
          placeholder: '\$0',
          keyboardType: TextInputType.number,
        ),
        Padding(
          padding: const EdgeInsets.only(top: 4, bottom: 16),
          child: Text(
            'Include interest, dividends, retirement income',
            style: UiTypography.body3r.copyWith(color: UiColors.textSecondary),
          ),
        ),

        _buildTextField(
          '4(b) Deductions',
          value: state.deductions,
          onChanged: (String val) => context.read<FormW4Cubit>().deductionsChanged(val),
          placeholder: '\$0',
          keyboardType: TextInputType.number,
        ),
        Padding(
          padding: const EdgeInsets.only(top: 4, bottom: 16),
          child: Text(
            'If you expect to claim deductions other than the standard deduction',
            style: UiTypography.body3r.copyWith(color: UiColors.textSecondary),
          ),
        ),

        _buildTextField(
          '4(c) Extra withholding',
          value: state.extraWithholding,
          onChanged: (String val) => context.read<FormW4Cubit>().extraWithholdingChanged(val),
          placeholder: '\$0',
          keyboardType: TextInputType.number,
        ),
        Padding(
          padding: const EdgeInsets.only(top: 4, bottom: 16),
          child: Text(
            'Any additional tax you want withheld each pay period',
            style: UiTypography.body3r.copyWith(color: UiColors.textSecondary),
          ),
        ),
      ],
    );
  }

  Widget _buildStep6(BuildContext context, FormW4State 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(
                'Your W-4 Summary',
                style: UiTypography.headline4m.copyWith(fontSize: 14),
              ),
              const SizedBox(height: 12),
              _buildSummaryRow(
                'Name',
                '${state.firstName} ${state.lastName}',
              ),
              _buildSummaryRow(
                'SSN',
                '***-**-${state.ssn.length >= 4 ? state.ssn.substring(state.ssn.length - 4) : '****'}',
              ),
              _buildSummaryRow(
                'Filing Status',
                _getFilingStatusLabel(state.filingStatus),
              ),
              if (_totalCredits(state) > 0)
                _buildSummaryRow(
                  'Credits',
                  '\$${_totalCredits(state)}',
                  valueColor: Colors.green[700],
                ),
            ],
          ),
        ),
        const SizedBox(height: 24),
        Container(
          padding: const EdgeInsets.all(16),
          decoration: BoxDecoration(
            color: Colors.amber[50],
            borderRadius: BorderRadius.circular(12),
          ),
          child: const Text(
            'Under penalties of perjury, I declare that this certificate, to the best of my knowledge and belief, is true, correct, and complete.',
            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<FormW4Cubit>().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, {Color? valueColor}) {
    return Padding(
      padding: const EdgeInsets.only(bottom: 8),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        children: <Widget>[
          Text(
            label,
            style: UiTypography.body2r.copyWith(color: UiColors.textSecondary),
          ),
          Text(
            value,
            style: UiTypography.body2m.copyWith(
              color: valueColor ?? UiColors.textPrimary,
            ),
          ),
        ],
      ),
    );
  }

  String _getFilingStatusLabel(String status) {
    switch (status) {
      case 'single':
        return 'Single';
      case 'married':
        return 'Married';
      case 'head_of_household':
        return 'Head of Household';
      default:
        return status;
    }
  }

  Widget _buildFooter(BuildContext context, FormW4State 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 != FormW4Status.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 == FormW4Status.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
                                ? 'Submit Form'
                                : 'Continue',
                          ),
                          if (state.currentStep < _steps.length - 1) ...<Widget>[
                            const SizedBox(width: 8),
                            const Icon(UiIcons.arrowRight, size: 16, color: UiColors.bgPopup),
                          ],
                        ],
                      ),
              ),
            ),
          ],
        ),
      ),
    );
  }
}
