import 'package:flutter_bloc/flutter_bloc.dart';
import '../../../domain/entities/tax_form_entity.dart';
import '../../../domain/usecases/submit_tax_form_usecase.dart';
import 'form_w4_state.dart';

class FormW4Cubit extends Cubit<FormW4State> {
  final SubmitTaxFormUseCase _submitTaxFormUseCase;

  FormW4Cubit(this._submitTaxFormUseCase) : super(const FormW4State());

  void nextStep(int totalSteps) {
    if (state.currentStep < totalSteps - 1) {
      emit(state.copyWith(currentStep: state.currentStep + 1));
    } else {
      submit();
    }
  }

  void previousStep() {
    if (state.currentStep > 0) {
      emit(state.copyWith(currentStep: state.currentStep - 1));
    }
  }

  // Personal Info
  void firstNameChanged(String value) => emit(state.copyWith(firstName: value));
  void lastNameChanged(String value) => emit(state.copyWith(lastName: value));
  void ssnChanged(String value) => emit(state.copyWith(ssn: value));
  void addressChanged(String value) => emit(state.copyWith(address: value));
  void cityStateZipChanged(String value) => emit(state.copyWith(cityStateZip: value));

  // Form Data
  void filingStatusChanged(String value) => emit(state.copyWith(filingStatus: value));
  void multipleJobsChanged(bool value) => emit(state.copyWith(multipleJobs: value));
  void qualifyingChildrenChanged(int value) => emit(state.copyWith(qualifyingChildren: value));
  void otherDependentsChanged(int value) => emit(state.copyWith(otherDependents: value));
  
  // Adjustments
  void otherIncomeChanged(String value) => emit(state.copyWith(otherIncome: value));
  void deductionsChanged(String value) => emit(state.copyWith(deductions: value));
  void extraWithholdingChanged(String value) => emit(state.copyWith(extraWithholding: value));
  void signatureChanged(String value) => emit(state.copyWith(signature: value));

  Future<void> submit() async {
    emit(state.copyWith(status: FormW4Status.submitting));
    try {
      await _submitTaxFormUseCase(
        TaxFormType.w4,
        <String, dynamic>{
          'firstName': state.firstName,
          'lastName': state.lastName,
          'ssn': state.ssn,
          'filingStatus': state.filingStatus,
          'multipleJobs': state.multipleJobs,
          'signature': state.signature,
          // ... add other fields as needed
        },
      );
      emit(state.copyWith(status: FormW4Status.success));
    } catch (e) {
      emit(state.copyWith(
        status: FormW4Status.failure,
        errorMessage: e.toString(),
      ));
    }
  }
}
