import 'package:bloc/bloc.dart';
import 'package:business_panel/core/config/api_config.dart';
import 'package:business_panel/core/services/token_storage_service.dart';
import 'package:business_panel/domain/entities/discount_entity.dart';
import 'package:dio/dio.dart';
import 'package:flutter/foundation.dart';

part 'home_event.dart';
part 'home_state.dart';

class HomeBloc extends Bloc<HomeEvent, HomeState> {
  final Dio _dio = Dio();
  final TokenStorageService _tokenStorage = TokenStorageService();

  HomeBloc() : super(HomeInitial()) {
    on<FetchDiscounts>((event, emit) async {
      emit(HomeLoading());
      try {
        final token = await _tokenStorage.getAccessToken();
        if (token == null || token.isEmpty) {
          emit(HomeError("خطای احراز هویت. لطفا دوباره وارد شوید."));
          return;
        }

        final response = await _dio.get(
          ApiConfig.getDiscounts,
          options: Options(
            headers: {'Authorization': 'Bearer $token'},
          ),
        );

        if (response.statusCode == 200 && response.data['data'] != null) {
          final List<dynamic> data = response.data['data'];
          final discounts = data.map((json) => DiscountEntity.fromJson(json)).toList();
          emit(HomeLoaded(discounts));
        } else {
          emit(HomeError(response.data['message'] ?? 'خطا در دریافت اطلاعات'));
        }
      } on DioException catch (e) {
        // Log Dio error
        if (kDebugMode) {
          print('DioException in HomeBloc: ${e.response?.data}');
        }
        emit(HomeError(e.response?.data['message'] ?? 'خطای شبکه'));
      } catch (e, stackTrace) {
        // Log any other error
        if (kDebugMode) {
          print('Error in HomeBloc: $e');
          print(stackTrace);
        }
        emit(HomeError('خطای پیش‌بینی نشده رخ داد: ${e.toString()}'));
      }
    });
  }
}