// lib/presentation/discount_management/bloc/discount_management_bloc.dart
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/core/utils/logging_interceptor.dart';
import 'package:business_panel/domain/entities/discount_entity.dart';
import 'package:dio/dio.dart';
import 'package:flutter/foundation.dart';

part 'discount_management_event.dart';
part 'discount_management_state.dart';

class DiscountManagementBloc extends Bloc<DiscountManagementEvent, DiscountManagementState> {
  final Dio _dio = Dio();
  final TokenStorageService _tokenStorage = TokenStorageService();

  DiscountManagementBloc() : super(DiscountManagementInitial()) {
    _dio.interceptors.add(LoggingInterceptor());

    on<FetchManagedDiscounts>((event, emit) async {
      await _fetchDiscounts(emit, status: event.status);
    });

    on<SearchManagedDiscounts>((event, emit) async {
      await _fetchDiscounts(emit, searchQuery: event.query, status: event.status);
    });

    // **NEW EVENT HANDLER**
    on<DeleteDiscount>((event, emit) async {
      emit(DiscountDeleteInProgress());
      try {
        final token = await _tokenStorage.getAccessToken();
        if (token == null || token.isEmpty) {
          emit(DiscountDeleteFailure("خطای احراز هویت."));
          return;
        }

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

        if (response.statusCode == 200) {
          emit(DiscountDeleteSuccess("تخفیف با موفقیت حذف شد."));
        } else {
          emit(DiscountDeleteFailure(response.data['message'] ?? 'خطا در حذف تخفیف'));
        }
      } on DioException catch (e) {
        emit(DiscountDeleteFailure(e.response?.data['message'] ?? 'خطای شبکه'));
      } catch (e) {
        emit(DiscountDeleteFailure('خطای پیش‌بینی نشده: ${e.toString()}'));
      }
    });
  }

  Future<void> _fetchDiscounts(Emitter<DiscountManagementState> emit,
      {String? searchQuery, int? status}) async {
    // To prevent showing old data, we start with loading
    // but only if the current state is not about deletion status
    if (state is! DiscountDeleteSuccess && state is! DiscountDeleteFailure) {
       emit(DiscountManagementLoading());
    }

    try {
      final token = await _tokenStorage.getAccessToken();
      if (token == null || token.isEmpty) {
        emit(DiscountManagementError("خطای احراز هویت. لطفا دوباره وارد شوید."));
        return;
      }

      String url = ApiConfig.getDiscounts;
      Map<String, dynamic> queryParameters = {};

      if (status != null) {
        queryParameters['status'] = status;
      }
      if (searchQuery != null && searchQuery.isNotEmpty) {
        queryParameters['search'] = searchQuery;
      }

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

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