import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:krow_domain/krow_domain.dart';
import 'package:uuid/uuid.dart';

import '../../../domain/usecases/submit_w4_form_usecase.dart';
import 'form_w4_state.dart';

class FormW4Cubit extends Cubit<FormW4State> {
  final SubmitW4FormUseCase _submitW4FormUseCase;
  String _formId = '';

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

  void initialize(TaxForm? form) {
    if (form == null || form.formData.isEmpty) {
      emit(const FormW4State()); // Reset
      return;
    }
    
    final Map<String, dynamic> data = form.formData;
    _formId = form.id;
    
    // Combine address parts if needed, or take existing
    final String city = data['city'] as String? ?? '';
    final String stateVal = data['state'] as String? ?? '';
    final String zip = data['zipCode'] as String? ?? '';
    final String cityStateZip = '$city, $stateVal $zip'.trim();

    emit(FormW4State(
      firstName: data['firstName'] as String? ?? '',
      lastName: data['lastName'] as String? ?? '',
      ssn: data['ssn'] as String? ?? '',
      address: data['address'] as String? ?? '',
      cityStateZip: cityStateZip.contains(',') ? cityStateZip : '',
      filingStatus: data['filingStatus'] as String? ?? '',
      multipleJobs: data['multipleJobs'] as bool? ?? false,
      qualifyingChildren: data['qualifyingChildren'] as int? ?? 0,
      otherDependents: data['otherDependents'] as int? ?? 0,
      otherIncome: data['otherIncome'] as String? ?? '',
      deductions: data['deductions'] as String? ?? '',
      extraWithholding: data['extraWithholding'] as String? ?? '',
      signature: data['signature'] as String? ?? '',
    ));
  }

  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 {
      final Map<String, dynamic> formData = {
        'firstName': state.firstName,
        'lastName': state.lastName,
        'ssn': state.ssn,
        'address': state.address,
        'cityStateZip': state.cityStateZip, // Note: Repository should split this if needed.
        'filingStatus': state.filingStatus,
        'multipleJobs': state.multipleJobs,
        'qualifyingChildren': state.qualifyingChildren,
        'otherDependents': state.otherDependents,
        'otherIncome': state.otherIncome,
        'deductions': state.deductions,
        'extraWithholding': state.extraWithholding,
        'signature': state.signature,
      };

      final W4TaxForm form = W4TaxForm(
        id: _formId.isNotEmpty ? _formId : const Uuid().v4(),
        title: 'Form W-4',
        formData: formData,
      );

      await _submitW4FormUseCase(form);
      emit(state.copyWith(status: FormW4Status.success));
    } catch (e) {
      emit(state.copyWith(
        status: FormW4Status.failure,
        errorMessage: e.toString(),
      ));
    }
  }
}
