import 'dart:developer';

import 'package:bloc/bloc.dart';
import 'package:tanami_app/features/MainScreens/Invest/domain/model/available_io_model.dart';
import 'package:tanami_app/features/MainScreens/Invest/domain/model/closed_io_model.dart';

import '../../../../../Api_Helper/base_manager.dart';
import '../../domain/repository/io_api.dart';
import 'tab_event.dart';
import 'tab_state.dart';

class TabBloc extends Bloc<TabEvent, TabState> {
  TabBloc() : super(TabState(AvailableIOModel(), ClosedIOModel(), false, '')) {
    on<LoadAvailableItems>(_onLoadAvailableItems);
    on<LoadClosedItems>(_onLoadClosedItems);
  }

  Future<void> _onLoadAvailableItems(
      LoadAvailableItems event, Emitter<TabState> emit) async {
    emit(state.copyWith(loading: true));
    try {
      ResponseData response = await IOApi().availableIOAPI();
      log(response.data.toString());
      if (response.status == ResponseStatus.SUCCESS) {
        AvailableIOModel availableIOModel =
            AvailableIOModel.fromJson(response.data);
        emit(state.copyWith(availableItems: availableIOModel, loading: false));
      } else {
        emit(state.copyWith(errorMessage: response.message, loading: false));
      }
    } catch (e) {
      emit(state.copyWith(
          errorMessage: 'Failed to fetch available items: $e', loading: false));
    }
  }

  void _onLoadClosedItems(LoadClosedItems event, Emitter<TabState> emit) async {
    emit(state.copyWith(loading: true));
    try {
      ResponseData response = await IOApi().closedIOAPI();
      if (response.status == ResponseStatus.SUCCESS) {
        ClosedIOModel closedIOModel = ClosedIOModel.fromJson(response.data);
        emit(state.copyWith(closedItems: closedIOModel, loading: false));
      } else {
        emit(state.copyWith(errorMessage: response.message, loading: false));
      }
    } catch (e) {
      emit(state.copyWith(
          errorMessage: 'Failed to fetch available items: $e', loading: false));
    }
  }
}
