import 'package:core_localization/core_localization.dart';
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) {
    final i18n = Translations.of(context).staff_compliance.tax_forms.w4;
    
    final List<Map<String, String>> steps = <Map<String, String>>[
      <String, String>{'title': i18n.steps.personal, 'subtitle': i18n.step_label(current: '1', total: '5')},
      <String, String>{'title': i18n.steps.filing, 'subtitle': i18n.step_label(current: '1c', total: '5')},
      <String, String>{'title': i18n.steps.multiple_jobs, 'subtitle': i18n.step_label(current: '2', total: '5')},
      <String, String>{'title': i18n.steps.dependents, 'subtitle': i18n.step_label(current: '3', total: '5')},
      <String, String>{'title': i18n.steps.adjustments, 'subtitle': i18n.step_label(current: '4', total: '5')},
      <String, String>{'title': i18n.steps.review, 'subtitle': i18n.step_label(current: '5', total: '5')},
    ];

    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) {
            UiSnackbar.show(
              context,
              message: translateErrorKey(state.errorMessage ?? 'An error occurred'),
              type: UiSnackbarType.error,
              margin: const EdgeInsets.only(
                left: UiConstants.space4,
                right: UiConstants.space4,
                bottom: 100,
              ),
            );
          }
        },
        builder: (BuildContext context, FormW4State state) {
          if (state.status == FormW4Status.success) return _buildSuccessView(i18n);

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

  Widget _buildSuccessView(TranslationsStaffComplianceTaxFormsW4En i18n) {
    return Scaffold(
      backgroundColor: UiColors.background,
      body: Center(
        child: Padding(
          padding: const EdgeInsets.all(UiConstants.space6),
          child: Container(
            padding: const EdgeInsets.all(UiConstants.space8),
            decoration: BoxDecoration(
              color: UiColors.bgPopup,
              borderRadius: UiConstants.radiusLg,
              border: Border.all(color: UiColors.border),
            ),
            child: Column(
              mainAxisSize: MainAxisSize.min,
              children: <Widget>[
                Container(
                  width: 64,
                  height: 64,
                  decoration: BoxDecoration(
                    color: UiColors.tagSuccess,
                    shape: BoxShape.circle,
                  ),
                  child: const Icon(
                    UiIcons.success,
                    color: UiColors.textSuccess,
                    size: 32,
                  ),
                ),
                const SizedBox(height: UiConstants.space4),
                Text(
                  i18n.submitted_title,
                  style: UiTypography.headline4m.textPrimary,
                ),
                const SizedBox(height: UiConstants.space2),
                Text(
                  i18n.submitted_desc,
                  textAlign: TextAlign.center,
                  style: UiTypography.body2r.textSecondary,
                ),
                const SizedBox(height: UiConstants.space6),
                SizedBox(
                  width: double.infinity,
                  child: ElevatedButton(
                    onPressed: () => Modular.to.pop(true),
                    style: ElevatedButton.styleFrom(
                      backgroundColor: UiColors.primary,
                      foregroundColor: UiColors.white,
                      padding: const EdgeInsets.symmetric(
                        vertical: UiConstants.space4,
                      ),
                      shape: RoundedRectangleBorder(
                        borderRadius: UiConstants.radiusLg,
                      ),
                      elevation: 0,
                    ),
                    child: Text(i18n.back_to_docs),
                  ),
                ),
              ],
            ),
          ),
        ),
      ),
    );
  }

  Widget _buildHeader(
    BuildContext context,
    FormW4State state,
    List<Map<String, String>> steps,
    TranslationsStaffComplianceTaxFormsW4En i18n,
  ) {
    return Container(
      color: UiColors.primary,
      padding: const EdgeInsets.only(
        top: 60,
        bottom: UiConstants.space6,
        left: UiConstants.space5,
        right: UiConstants.space5,
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: <Widget>[
          Row(
            children: <Widget>[
              GestureDetector(
                onTap: () => Modular.to.pop(),
                child: const Icon(
                  UiIcons.arrowLeft,
                  color: UiColors.white,
                  size: 24,
                ),
              ),
              const SizedBox(width: UiConstants.space3),
              Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: <Widget>[
                  Text(
                    i18n.title,
                    style: UiTypography.headline4m.white,
                  ),
                  Text(
                    i18n.subtitle,
                    style: UiTypography.body3r.copyWith(
                      color: UiColors.white.withValues(alpha: 0.7),
                    ),
                  ),
                ],
              ),
            ],
          ),
          const SizedBox(height: UiConstants.space6),
          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.white
                              : UiColors.white.withValues(alpha: 0.3),
                          borderRadius: UiConstants.radiusXs,
                        ),
                      ),
                    ),
                    if (!isLast) const SizedBox(width: 4),
                  ],
                ),
              );
            }).toList(),
          ),
          const SizedBox(height: UiConstants.space2),
          Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: <Widget>[
              Text(
                i18n.step_label(
                  current: (state.currentStep + 1).toString(),
                  total: steps.length.toString(),
                ),
                style: UiTypography.body3r.copyWith(
                  color: UiColors.white.withValues(alpha: 0.7),
                ),
              ),
              Text(
                steps[state.currentStep]['title']!,
                style: UiTypography.body3m.white.copyWith(
                  fontWeight: FontWeight.w500,
                ),
              ),
            ],
          ),
        ],
      ),
    );
  }

  Widget _buildCurrentStep(
    BuildContext context,
    FormW4State state,
    TranslationsStaffComplianceTaxFormsW4En i18n,
  ) {
    switch (state.currentStep) {
      case 0:
        return _buildStep1(context, state, i18n);
      case 1:
        return _buildStep2(context, state, i18n);
      case 2:
        return _buildStep3(context, state, i18n);
      case 3:
        return _buildStep4(context, state, i18n);
      case 4:
        return _buildStep5(context, state, i18n);
      case 5:
        return _buildStep6(context, state, i18n);
      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.textSecondary.copyWith(
            fontWeight: FontWeight.w500,
          ),
        ),
        const SizedBox(height: UiConstants.space1 + 2),
        TextField(
          controller: TextEditingController(text: value)
            ..selection = TextSelection.fromPosition(
              TextPosition(offset: value.length),
            ),
          onChanged: onChanged,
          keyboardType: keyboardType,
          style: UiTypography.body2r.textPrimary,
          decoration: InputDecoration(
            hintText: placeholder,
            hintStyle: UiTypography.body2r.textPlaceholder,
            filled: true,
            fillColor: UiColors.bgPopup,
            contentPadding: const EdgeInsets.symmetric(
              horizontal: UiConstants.space4,
              vertical: UiConstants.space4,
            ),
            border: OutlineInputBorder(
              borderRadius: UiConstants.radiusLg,
              borderSide: const BorderSide(color: UiColors.border),
            ),
            enabledBorder: OutlineInputBorder(
              borderRadius: UiConstants.radiusLg,
              borderSide: const BorderSide(color: UiColors.border),
            ),
            focusedBorder: OutlineInputBorder(
              borderRadius: UiConstants.radiusLg,
              borderSide: const BorderSide(color: UiColors.primary),
            ),
          ),
        ),
      ],
    );
  }

  Widget _buildStep1(
    BuildContext context,
    FormW4State state,
    TranslationsStaffComplianceTaxFormsW4En i18n,
  ) {
    return Column(
      children: <Widget>[
        Row(
          children: <Widget>[
            Expanded(
              child: _buildTextField(
                i18n.fields.first_name,
                value: state.firstName,
                onChanged: (String val) => context.read<FormW4Cubit>().firstNameChanged(val),
                placeholder: i18n.fields.placeholder_john,
              ),
            ),
            const SizedBox(width: UiConstants.space3),
            Expanded(
              child: _buildTextField(
                i18n.fields.last_name,
                value: state.lastName,
                onChanged: (String val) => context.read<FormW4Cubit>().lastNameChanged(val),
                placeholder: i18n.fields.placeholder_smith,
              ),
            ),
          ],
        ),
        const SizedBox(height: UiConstants.space4),
        _buildTextField(
          i18n.fields.ssn,
          value: state.ssn,
          placeholder: i18n.fields.placeholder_ssn,
          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: UiConstants.space4),
        _buildTextField(
          i18n.fields.address,
          value: state.address,
          onChanged: (String val) => context.read<FormW4Cubit>().addressChanged(val),
          placeholder: i18n.fields.placeholder_address,
        ),
        const SizedBox(height: UiConstants.space4),
        _buildTextField(
          i18n.fields.city_state_zip,
          value: state.cityStateZip,
          onChanged: (String val) => context.read<FormW4Cubit>().cityStateZipChanged(val),
          placeholder: i18n.fields.placeholder_csz,
        ),
      ],
    );
  }

  Widget _buildStep2(
    BuildContext context,
    FormW4State state,
    TranslationsStaffComplianceTaxFormsW4En i18n,
  ) {
    return Column(
      children: <Widget>[
        Container(
          padding: const EdgeInsets.all(UiConstants.space4),
          decoration: BoxDecoration(
            color: UiColors.tagActive,
            borderRadius: UiConstants.radiusLg,
          ),
          child: Row(
            children: <Widget>[
              const Icon(UiIcons.info, color: UiColors.primary, size: 20),
              const SizedBox(width: UiConstants.space3),
              Expanded(
                child: Text(
                  i18n.fields.filing_info,
                  style: UiTypography.body2r.textPrimary,
                ),
              ),
            ],
          ),
        ),
        const SizedBox(height: UiConstants.space6),
        _buildRadioOption(
          context,
          state,
          'SINGLE',
          i18n.fields.single,
          null,
        ),
        const SizedBox(height: UiConstants.space3),
        _buildRadioOption(
          context,
          state,
          'MARRIED',
          i18n.fields.married,
          null,
        ),
        const SizedBox(height: UiConstants.space3),
        _buildRadioOption(
          context,
          state,
          'HEAD',
          i18n.fields.head,
          i18n.fields.head_desc,
        ),
      ],
    );
  }

  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(UiConstants.space4),
        decoration: BoxDecoration(
          color: UiColors.bgPopup,
          borderRadius: UiConstants.radiusLg,
          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 : UiColors.border,
                  width: isSelected ? UiConstants.radiusMdValue : 2,
                ),
              ),
            ),
            const SizedBox(width: UiConstants.space3),
            Expanded(
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: <Widget>[
                  Text(
                    label,
                    style: UiTypography.body2m.textPrimary,
                  ),
                  if (subLabel != null) ...<Widget>[
                    const SizedBox(height: 4),
                    Text(
                      subLabel,
                      style: UiTypography.body3r.textSecondary,
                    ),
                  ],
                ],
              ),
            ),
          ],
        ),
      ),
    );
  }

  Widget _buildStep3(
    BuildContext context,
    FormW4State state,
    TranslationsStaffComplianceTaxFormsW4En i18n,
  ) {
    return Column(
      children: <Widget>[
        Container(
          padding: const EdgeInsets.all(UiConstants.space4),
          decoration: BoxDecoration(
            color: UiColors.accent.withValues(alpha: 0.1),
            borderRadius: UiConstants.radiusLg,
          ),
          child: Row(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: <Widget>[
              const Icon(
                UiIcons.help,
                color: UiColors.accent,
                size: 20,
              ),
              const SizedBox(width: UiConstants.space3),
              Expanded(
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: <Widget>[
                    Text(
                      i18n.fields.multiple_jobs_title,
                      style: UiTypography.body2m.accent,
                    ),
                    const SizedBox(height: 4),
                    Text(
                      i18n.fields.multiple_jobs_desc,
                      style: UiTypography.body3r.accent,
                    ),
                  ],
                ),
              ),
            ],
          ),
        ),
        const SizedBox(height: UiConstants.space6),
        GestureDetector(
          onTap: () =>
              context.read<FormW4Cubit>().multipleJobsChanged(!state.multipleJobs),
          child: Container(
            padding: const EdgeInsets.all(UiConstants.space4),
            decoration: BoxDecoration(
              color: UiColors.bgPopup,
              borderRadius: UiConstants.radiusLg,
              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: UiConstants.radiusMd,
                    border: Border.all(
                      color: state.multipleJobs ? UiColors.primary : UiColors.border,
                    ),
                  ),
                  child: state.multipleJobs
                      ? const Icon(
                          UiIcons.check,
                          color: UiColors.white,
                          size: 16,
                        )
                      : null,
                ),
                const SizedBox(width: 12),
                Expanded(
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: <Widget>[
                      Text(
                        i18n.fields.multiple_jobs_check,
                        style: UiTypography.body2m.textPrimary,
                      ),
                      const SizedBox(height: 4),
                      Text(
                        i18n.fields.two_jobs_desc,
                        style: UiTypography.body3r.textSecondary,
                      ),
                    ],
                  ),
                ),
              ],
            ),
          ),
        ),
        const SizedBox(height: UiConstants.space4),
        Text(
          i18n.fields.multiple_jobs_not_apply,
          textAlign: TextAlign.center,
          style: UiTypography.body3r.textSecondary,
        ),
      ],
    );
  }

  Widget _buildStep4(
    BuildContext context,
    FormW4State state,
    TranslationsStaffComplianceTaxFormsW4En i18n,
  ) {
    return Column(
      children: <Widget>[
        Container(
          padding: const EdgeInsets.all(UiConstants.space4),
          decoration: BoxDecoration(
            color: UiColors.tagActive,
            borderRadius: UiConstants.radiusLg,
          ),
          child: Row(
            children: <Widget>[
              const Icon(UiIcons.info, color: UiColors.primary, size: 20),
              const SizedBox(width: UiConstants.space3),
              Expanded(
                child: Text(
                  i18n.fields.dependents_info,
                  style: UiTypography.body2r.textPrimary,
                ),
              ),
            ],
          ),
        ),
        const SizedBox(height: UiConstants.space6),
        Container(
          padding: const EdgeInsets.all(UiConstants.space4),
          decoration: BoxDecoration(
            color: UiColors.bgPopup,
            borderRadius: UiConstants.radiusLg,
            border: Border.all(color: UiColors.border),
          ),
          child: Column(
            children: <Widget>[
              _buildCounter(
                context,
                state,
                i18n.fields.children_under_17,
                i18n.fields.children_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,
                i18n.fields.other_dependents,
                i18n.fields.other_each,
                (FormW4State s) => s.otherDependents,
                (int val) => context.read<FormW4Cubit>().otherDependentsChanged(val),
              ),
            ],
          ),
        ),
        if (_totalCredits(state) > 0) ...<Widget>[
          const SizedBox(height: UiConstants.space4),
          Container(
            padding: const EdgeInsets.all(UiConstants.space4),
            decoration: BoxDecoration(
              color: UiColors.tagSuccess,
              borderRadius: UiConstants.radiusLg,
            ),
            child: Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: <Widget>[
                Text(
                  i18n.fields.total_credits,
                  style: UiTypography.body2m.textSuccess,
                ),
                Text(
                  '\$${_totalCredits(state)}',
                  style: UiTypography.body2b.textSuccess.copyWith(
                    fontSize: 18,
                  ),
                ),
              ],
            ),
          ),
        ],
      ],
    );
  }

  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: UiColors.tagSuccess,
                borderRadius: UiConstants.radiusLg,
              ),
              child: Text(
                badge,
                style: UiTypography.footnote2b.textSuccess,
              ),
            ),
          ],
        ),
        const SizedBox(height: UiConstants.space3),
        Row(
          children: <Widget>[
            _buildCircleBtn(
              UiIcons.minus,
              () => onChanged(value > 0 ? value - 1 : 0),
            ),
            SizedBox(
              width: 48,
              child: Text(
                value.toString(),
                textAlign: TextAlign.center,
                style: UiTypography.headline3m.textPrimary.copyWith(
                  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,
    TranslationsStaffComplianceTaxFormsW4En i18n,
  ) {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: <Widget>[
        Text(
          i18n.fields.adjustments_info,
          style: UiTypography.body2r.textSecondary,
        ),
        const SizedBox(height: UiConstants.space6),
        _buildTextField(
          i18n.fields.other_income,
          value: state.otherIncome,
          onChanged: (String val) => context.read<FormW4Cubit>().otherIncomeChanged(val),
          placeholder: i18n.fields.hints.zero,
          keyboardType: TextInputType.number,
        ),
        Padding(
          padding: const EdgeInsets.only(top: 4, bottom: 16),
          child: Text(
            i18n.fields.other_income_desc,
            style: UiTypography.body3r.textSecondary,
          ),
        ),

        _buildTextField(
          i18n.fields.deductions,
          value: state.deductions,
          onChanged: (String val) => context.read<FormW4Cubit>().deductionsChanged(val),
          placeholder: i18n.fields.hints.zero,
          keyboardType: TextInputType.number,
        ),
        Padding(
          padding: const EdgeInsets.only(top: 4, bottom: 16),
          child: Text(
            i18n.fields.deductions_desc,
            style: UiTypography.body3r.textSecondary,
          ),
        ),

        _buildTextField(
          i18n.fields.extra_withholding,
          value: state.extraWithholding,
          onChanged: (String val) => context.read<FormW4Cubit>().extraWithholdingChanged(val),
          placeholder: i18n.fields.hints.zero,
          keyboardType: TextInputType.number,
        ),
        Padding(
          padding: const EdgeInsets.only(top: 4, bottom: 16),
          child: Text(
            i18n.fields.extra_withholding_desc,
            style: UiTypography.body3r.textSecondary,
          ),
        ),
      ],
    );
  }

  Widget _buildStep6(
    BuildContext context,
    FormW4State state,
    TranslationsStaffComplianceTaxFormsW4En i18n,
  ) {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: <Widget>[
        Container(
          padding: const EdgeInsets.all(UiConstants.space4),
          decoration: BoxDecoration(
            color: UiColors.bgPopup,
            borderRadius: UiConstants.radiusLg,
            border: Border.all(color: UiColors.border),
          ),
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: <Widget>[
              Text(
                i18n.fields.summary_title,
                style: UiTypography.headline4m.copyWith(fontSize: 14),
              ),
              const SizedBox(height: UiConstants.space3),
              _buildSummaryRow(
                i18n.fields.summary_name,
                '${state.firstName} ${state.lastName}',
              ),
              _buildSummaryRow(
                i18n.fields.summary_ssn,
                '***-**-${state.ssn.length >= 4 ? state.ssn.substring(state.ssn.length - 4) : '****'}',
              ),
              _buildSummaryRow(
                i18n.fields.summary_filing,
                _getFilingStatusLabel(state.filingStatus),
              ),
              if (_totalCredits(state) > 0)
                _buildSummaryRow(
                  i18n.fields.summary_credits,
                  '\$${_totalCredits(state)}',
                  valueColor: UiColors.textSuccess,
                ),
            ],
          ),
        ),
        const SizedBox(height: UiConstants.space6),
        Container(
          padding: const EdgeInsets.all(UiConstants.space4),
          decoration: BoxDecoration(
            color: UiColors.accent.withValues(alpha: 0.1),
            borderRadius: UiConstants.radiusLg,
          ),
          child: Text(
            i18n.fields.perjury_declaration,
            style: UiTypography.body3r.textWarning.copyWith(fontSize: 12),
          ),
        ),
        const SizedBox(height: UiConstants.space6),
        Text(
          i18n.fields.signature_label,
          style: UiTypography.body3m.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: i18n.fields.signature_hint,
            filled: true,
            fillColor: UiColors.bgPopup,
            contentPadding: const EdgeInsets.symmetric(
              horizontal: UiConstants.space4,
              vertical: UiConstants.space4,
            ),
            border: OutlineInputBorder(
              borderRadius: UiConstants.radiusLg,
              borderSide: const BorderSide(color: UiColors.border),
            ),
            enabledBorder: OutlineInputBorder(
              borderRadius: UiConstants.radiusLg,
              borderSide: const BorderSide(color: UiColors.border),
            ),
            focusedBorder: OutlineInputBorder(
              borderRadius: UiConstants.radiusLg,
              borderSide: const BorderSide(color: UiColors.primary),
            ),
          ),
          style: const TextStyle(fontFamily: 'Cursive', fontSize: 18),
        ),
        const SizedBox(height: UiConstants.space4),
        Text(
          i18n.fields.date_label,
          style: UiTypography.body3m.textSecondary,
        ),
        const SizedBox(height: 6),
        Container(
          width: double.infinity,
          padding: const EdgeInsets.symmetric(
            horizontal: UiConstants.space4,
            vertical: UiConstants.space4,
          ),
          decoration: BoxDecoration(
            color: UiColors.bgSecondary,
            borderRadius: UiConstants.radiusLg,
            border: Border.all(color: UiColors.border),
          ),
          child: Text(
            DateTime.now().toString().split(' ')[0],
            style: UiTypography.body2r.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.textSecondary,
          ),
          Text(
            value,
            style: UiTypography.body2m.copyWith(
              color: valueColor ?? UiColors.textPrimary,
            ),
          ),
        ],
      ),
    );
  }

  String _getFilingStatusLabel(String status) {
    final i18n = Translations.of(context).staff_compliance.tax_forms.w4.fields;
    switch (status) {
      case 'SINGLE':
        return i18n.status_single;
      case 'MARRIED':
        return i18n.status_married;
      case 'HEAD':
        return i18n.status_head;
      default:
        return status;
    }
  }

  Widget _buildFooter(
    BuildContext context,
    FormW4State state,
    List<Map<String, String>> steps,
  ) {
    final i18n = Translations.of(context).staff_compliance.tax_forms.w4;

    return Container(
      padding: const EdgeInsets.all(UiConstants.space4),
      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: UiConstants.space3),
                  child: OutlinedButton(
                    onPressed: () => _handleBack(context),
                    style: OutlinedButton.styleFrom(
                      padding: const EdgeInsets.symmetric(
                        vertical: UiConstants.space4,
                      ),
                      side: const BorderSide(color: UiColors.border),
                      shape: RoundedRectangleBorder(
                        borderRadius: UiConstants.radiusLg,
                      ),
                    ),
                    child: Row(
                      mainAxisAlignment: MainAxisAlignment.center,
                      children: <Widget>[
                        const Icon(
                          UiIcons.arrowLeft,
                          size: 16,
                          color: UiColors.textPrimary,
                        ),
                        const SizedBox(width: UiConstants.space2),
                        Text(
                          i18n.fields.back,
                          style: UiTypography.body2r.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: UiColors.bgSecondary,
                  foregroundColor: UiColors.white,
                  padding: const EdgeInsets.symmetric(
                    vertical: UiConstants.space4,
                  ),
                  shape: RoundedRectangleBorder(
                    borderRadius: UiConstants.radiusLg,
                  ),
                  elevation: 0,
                ),
                child: state.status == FormW4Status.submitting
                    ? const SizedBox(
                        width: 20,
                        height: 20,
                        child: CircularProgressIndicator(
                          color: UiColors.white,
                          strokeWidth: 2,
                        ),
                      )
                    : Row(
                        mainAxisAlignment: MainAxisAlignment.center,
                        children: <Widget>[
                          Text(
                            state.currentStep == steps.length - 1
                                ? i18n.fields.submit
                                : i18n.fields.kContinue,
                          ),
                          if (state.currentStep < steps.length - 1) ...<Widget>[
                            const SizedBox(width: UiConstants.space2),
                            const Icon(UiIcons.arrowRight, size: 16, color: UiColors.white),
                          ],
                        ],
                      ),
              ),
            ),
          ],
        ),
      ),
    );
  }
}
