import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:krow_core/core.dart';
import 'package:krow_domain/krow_domain.dart';
import '../../domain/arguments/add_bank_account_params.dart';
import '../../domain/usecases/add_bank_account_usecase.dart';
import '../../domain/usecases/get_bank_accounts_usecase.dart';
import 'bank_account_state.dart';

class BankAccountCubit extends Cubit<BankAccountState>
    with BlocErrorHandler<BankAccountState> {
  final GetBankAccountsUseCase _getBankAccountsUseCase;
  final AddBankAccountUseCase _addBankAccountUseCase;

  BankAccountCubit({
    required GetBankAccountsUseCase getBankAccountsUseCase,
    required AddBankAccountUseCase addBankAccountUseCase,
  }) : _getBankAccountsUseCase = getBankAccountsUseCase,
       _addBankAccountUseCase = addBankAccountUseCase,
       super(const BankAccountState());

  Future<void> loadAccounts() async {
    emit(state.copyWith(status: BankAccountStatus.loading));
    await handleError(
      emit: emit,
      action: () async {
        final List<BankAccount> accounts = await _getBankAccountsUseCase();
        emit(
          state.copyWith(
            status: BankAccountStatus.loaded,
            accounts: accounts,
          ),
        );
      },
      onError:
          (String errorKey) => state.copyWith(
            status: BankAccountStatus.error,
            errorMessage: errorKey,
          ),
    );
  }

  void toggleForm(bool show) {
    emit(state.copyWith(showForm: show));
  }

  Future<void> addAccount({
    required String bankName,
    required String routingNumber,
    required String accountNumber,
    required String type,
  }) async {
    emit(state.copyWith(status: BankAccountStatus.loading));

    // Create domain entity
    final BankAccount newAccount = BankAccount(
      id: '', // Generated by server usually
      userId: '', // Handled by Repo/Auth
      bankName: bankName,
      accountNumber: accountNumber,
      accountName: '',
      sortCode: routingNumber,
      type:
          type == 'CHECKING'
              ? BankAccountType.checking
              : BankAccountType.savings,
      last4:
          accountNumber.length > 4
              ? accountNumber.substring(accountNumber.length - 4)
              : accountNumber,
      isPrimary: false,
    );

    await handleError(
      emit: emit,
      action: () async {
        await _addBankAccountUseCase(AddBankAccountParams(account: newAccount));

        // Re-fetch to get latest state including server-generated IDs
        await loadAccounts();

        emit(
          state.copyWith(
            status: BankAccountStatus.accountAdded,
            showForm: false, // Close form on success
          ),
        );
      },
      onError:
          (String errorKey) => state.copyWith(
            status: BankAccountStatus.error,
            errorMessage: errorKey,
          ),
    );
  }
}

