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/reservation_entity.dart';
import 'package:dio/dio.dart';
import 'package:flutter/foundation.dart';

part 'reservation_event.dart';
part 'reservation_state.dart';

class ReservationBloc extends Bloc<ReservationEvent, ReservationState> {
  final Dio _dio = Dio();
  final TokenStorageService _tokenStorage = TokenStorageService();

  ReservationBloc() : super(ReservationInitial()) {
    _dio.interceptors.add(LoggingInterceptor());

    on<FetchReservations>((event, emit) async {
      await _fetchReservations(emit);
    });

    on<SearchReservations>((event, emit) async {
      await _fetchReservations(emit, searchQuery: event.query);
    });
  }

  Future<void> _fetchReservations(Emitter<ReservationState> emit, {String? searchQuery}) async {
    emit(ReservationLoading());
    try {
      final token = await _tokenStorage.getAccessToken();
      if (token == null || token.isEmpty) {
        emit(ReservationError("خطای احراز هویت. لطفا دوباره وارد شوید."));
        return;
      }

      String url = ApiConfig.getReservations;
      if (searchQuery != null && searchQuery.isNotEmpty) {
        url = '$url?search=$searchQuery'; 
      }

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

      if (response.statusCode == 200 && response.data['data'] != null) {
        final List<dynamic> data = response.data['data']['items'] ?? [];
        final reservations = data
            .map((json) => ReservationEntity.fromJson(json))
            .where((reservation) {
              if (reservation.discount.endDate == null) return true;
              return reservation.discount.endDate!.isAfter(DateTime.now());
            })
            .toList();
        emit(ReservationLoaded(reservations));
      } else {
        emit(ReservationError(response.data['message'] ?? 'خطا در دریافت اطلاعات'));
      }
    } on DioException catch (e) {
      if (kDebugMode) {
        print('DioException in ReservationBloc: ${e.response?.data}');
      }
      emit(ReservationError(e.response?.data['message'] ?? 'خطای شبکه'));
    } catch (e, stackTrace) {
      if (kDebugMode) {
        print('Error in ReservationBloc: $e');
        print(stackTrace);
      }
      emit(ReservationError('خطای پیش‌بینی نشده رخ داد: ${e.toString()}'));
    }
  }
}
