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

import '../../../domain/usecases/submit_i9_form_usecase.dart';
import 'form_i9_state.dart';

class FormI9Cubit extends Cubit<FormI9State> {
  final SubmitI9FormUseCase _submitI9FormUseCase;
  String _formId = '';

  FormI9Cubit(this._submitI9FormUseCase) : super(const FormI9State());

  void initialize(TaxForm? form) {
    if (form == null || form.formData.isEmpty) {
      emit(const FormI9State()); // Reset to empty if no form
      return;
    }
    
    final Map<String, dynamic> data = form.formData;
    _formId = form.id;
    emit(FormI9State(
      firstName: data['firstName'] as String? ?? '',
      lastName: data['lastName'] as String? ?? '',
      middleInitial: data['middleInitial'] as String? ?? '',
      otherLastNames: data['otherLastNames'] as String? ?? '',
      dob: data['dob'] as String? ?? '',
      ssn: data['ssn'] as String? ?? '',
      email: data['email'] as String? ?? '',
      phone: data['phone'] as String? ?? '',
      address: data['address'] as String? ?? '',
      aptNumber: data['aptNumber'] as String? ?? '',
      city: data['city'] as String? ?? '',
      state: data['state'] as String? ?? '',
      zipCode: data['zipCode'] as String? ?? '',
      citizenshipStatus: data['citizenshipStatus'] as String? ?? '',
      uscisNumber: data['uscisNumber'] as String? ?? '',
      admissionNumber: data['admissionNumber'] as String? ?? '',
      passportNumber: data['passportNumber'] as String? ?? '',
      countryIssuance: data['countryIssuance'] as String? ?? '',
      preparerUsed: data['preparerUsed'] as bool? ?? false,
      signature: data['signature'] as String? ?? '',
    ));
  }

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

  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 middleInitialChanged(String value) => emit(state.copyWith(middleInitial: value));
  void otherLastNamesChanged(String value) => emit(state.copyWith(otherLastNames: value));
  void dobChanged(String value) => emit(state.copyWith(dob: value));
  void ssnChanged(String value) => emit(state.copyWith(ssn: value));
  void emailChanged(String value) => emit(state.copyWith(email: value));
  void phoneChanged(String value) => emit(state.copyWith(phone: value));

  // Address
  void addressChanged(String value) => emit(state.copyWith(address: value));
  void aptNumberChanged(String value) => emit(state.copyWith(aptNumber: value));
  void cityChanged(String value) => emit(state.copyWith(city: value));
  void stateChanged(String value) => emit(state.copyWith(state: value));
  void zipCodeChanged(String value) => emit(state.copyWith(zipCode: value));

  // Citizenship
  void citizenshipStatusChanged(String value) => emit(state.copyWith(citizenshipStatus: value));
  void uscisNumberChanged(String value) => emit(state.copyWith(uscisNumber: value));
  void admissionNumberChanged(String value) => emit(state.copyWith(admissionNumber: value));
  void passportNumberChanged(String value) => emit(state.copyWith(passportNumber: value));
  void countryIssuanceChanged(String value) => emit(state.copyWith(countryIssuance: value));

  // Signature
  void preparerUsedChanged(bool value) => emit(state.copyWith(preparerUsed: value));
  void signatureChanged(String value) => emit(state.copyWith(signature: value));

  Future<void> submit() async {
    emit(state.copyWith(status: FormI9Status.submitting));
    try {
      final Map<String, dynamic> formData = {
        'firstName': state.firstName,
        'lastName': state.lastName,
        'middleInitial': state.middleInitial,
        'otherLastNames': state.otherLastNames,
        'dob': state.dob,
        'ssn': state.ssn,
        'email': state.email,
        'phone': state.phone,
        'address': state.address,
        'aptNumber': state.aptNumber,
        'city': state.city,
        'state': state.state,
        'zipCode': state.zipCode,
        'citizenshipStatus': state.citizenshipStatus,
        'uscisNumber': state.uscisNumber,
        'admissionNumber': state.admissionNumber,
        'passportNumber': state.passportNumber,
        'countryIssuance': state.countryIssuance,
        'preparerUsed': state.preparerUsed,
        'signature': state.signature,
      };

      final I9TaxForm form = I9TaxForm(
        id: _formId.isNotEmpty ? _formId : const Uuid().v4(),
        title: 'Form I-9',
        formData: formData,
      );

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