import 'package:flutter_bloc/flutter_bloc.dart';
import '../../../../core/network/dio_client.dart';
import '../../data/datasources/scenario_remote_datasource.dart';
import '../../data/repositories/scenario_repository_impl.dart';
import 'scenario_state.dart';

class ScenarioListCubit extends Cubit<ScenarioListState> {
  final ScenarioRepositoryImpl _repo;

  ScenarioListCubit()
      : _repo = ScenarioRepositoryImpl(
            ScenarioRemoteDatasource(DioClient.instance)),
        super(const ScenarioListState());

  Future<void> loadScenarios({int page = 1}) async {
    if (page == 1) {
      emit(state.copyWith(isLoading: true, error: () => null));
    } else {
      emit(state.copyWith(isLoadingMore: true));
    }

    try {
      final result = await _repo.getScenarios(
        page: page,
        difficulty: state.difficultyFilter,
        category: state.categoryFilter,
        risk: state.riskFilter,
      );

      final scenarios = page == 1
          ? result.scenarios
          : [...state.scenarios, ...result.scenarios];

      emit(state.copyWith(
        scenarios: scenarios,
        currentPage: result.page,
        totalPages: result.pages,
        isLoading: false,
        isLoadingMore: false,
      ));
    } catch (e) {
      emit(state.copyWith(
        isLoading: false,
        isLoadingMore: false,
        error: () => e.toString(),
      ));
    }
  }

  Future<void> loadMore() async {
    if (state.isLoadingMore || !state.hasMore) return;
    await loadScenarios(page: state.currentPage + 1);
  }

  void applyFilters({String? difficulty, String? category, String? risk}) {
    emit(ScenarioListState(
      difficultyFilter: difficulty,
      categoryFilter: category,
      riskFilter: risk,
    ));
    loadScenarios();
  }

  void clearFilters() {
    emit(const ScenarioListState());
    loadScenarios();
  }
}

class ScenarioDetailCubit extends Cubit<ScenarioDetailState> {
  final ScenarioRepositoryImpl _repo;

  ScenarioDetailCubit()
      : _repo = ScenarioRepositoryImpl(
            ScenarioRemoteDatasource(DioClient.instance)),
        super(const ScenarioDetailLoading());

  Future<void> loadDetail(String id) async {
    emit(const ScenarioDetailLoading());
    try {
      final scenario = await _repo.getDetail(id);
      emit(ScenarioDetailLoaded(scenario));
    } catch (e) {
      emit(ScenarioDetailError(e.toString()));
    }
  }
}