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/comment_entity.dart';
import 'package:business_panel/domain/entities/sales_stats_entity.dart';
import 'package:dio/dio.dart';
import 'package:flutter/foundation.dart';
import 'package:intl/intl.dart';

part 'sales_analysis_event.dart';
part 'sales_analysis_state.dart';

class SalesAnalysisBloc extends Bloc<SalesAnalysisEvent, SalesAnalysisState> {
  final Dio _dio = Dio();
  final TokenStorageService _tokenStorage = TokenStorageService();

  SalesAnalysisBloc() : super(SalesAnalysisInitial()) {
    on<FetchSalesData>((event, emit) async {
      emit(SalesAnalysisLoading());
      try {
        final token = await _tokenStorage.getAccessToken();
        if (token == null) {
          emit(const SalesAnalysisError("خطای احراز هویت."));
          return;
        }

        final response = await _dio.post(
          ApiConfig.getOrderStats,
          data: {
            'Discount': event.discountId,
            'Start': DateFormat('yyyy-MM-dd').format(event.date)
          },
          options: Options(headers: {'Authorization': 'Bearer $token'}),
        );

        if (response.statusCode == 200 && response.data['data'] != null) {
          emit(SalesAnalysisLoaded(
            salesData: response.data['data'],
            kpiStatus: KpiStatus.loading,
            commentStatus: CommentStatus.loading,
          ));
        } else {
          emit(SalesAnalysisError(
              response.data['message'] ?? 'خطا در دریافت اطلاعات نمودار'));
        }
      } catch (e) {
        emit(SalesAnalysisError('خطای پیش‌بینی نشده: ${e.toString()}'));
      }
    });

    on<FetchSalesStats>((event, emit) async {
      if (state is! SalesAnalysisLoaded) return;
      final currentState = state as SalesAnalysisLoaded;

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

        if (response.statusCode == 200 && response.data['data'] != null) {
          final stats = SalesStatsEntity.fromJson(response.data['data']);
          emit(currentState.copyWith(
              kpiStatus: KpiStatus.success, salesStats: stats));
        } else {
          emit(currentState.copyWith(
              kpiStatus: KpiStatus.failure,
              kpiErrorMessage: response.data['message']));
        }
      } catch (e) {
        emit(currentState.copyWith(
            kpiStatus: KpiStatus.failure,
            kpiErrorMessage: 'خطای شبکه در دریافت آمار'));
      }
    });

    on<FetchComments>((event, emit) async {
      debugPrint("[FetchComments] Event Started");
      if (state is! SalesAnalysisLoaded) return;
      final currentState = state as SalesAnalysisLoaded;

      try {
        final token = await _tokenStorage.getAccessToken();
        final url = ApiConfig.getComments(event.discountId);
        debugPrint("[FetchComments] Calling URL: $url");

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

        debugPrint("[FetchComments] Raw Response Data: ${response.data}");

        if (response.statusCode == 200 && response.data['data'] != null) {
          final List<dynamic> commentsList = response.data['data']['comments'] ?? [];
          
          final comments = commentsList.map((json) => CommentEntity.fromJson(json)).toList();
          debugPrint("[FetchComments] Success: Found ${comments.length} comments.");
          
          emit(currentState.copyWith(
              commentStatus: CommentStatus.success, comments: comments));
        } else {
          debugPrint("[FetchComments] Failure: Server returned status ${response.statusCode}");
          emit(currentState.copyWith(
              commentStatus: CommentStatus.failure,
              commentErrorMessage: response.data['message'] ?? 'خطا در دریافت پاسخ از سرور'));
        }
      } on DioException catch (e) {
        debugPrint("[FetchComments] DioException: ${e.message}");
        debugPrint("[FetchComments] DioException Response: ${e.response?.data}");
        emit(currentState.copyWith(
            commentStatus: CommentStatus.failure,
            commentErrorMessage: 'خطای شبکه در دریافت نظرات'));
      } catch (e) {
        debugPrint("[FetchComments] Generic Exception: ${e.toString()}");
        emit(currentState.copyWith(
            commentStatus: CommentStatus.failure,
            commentErrorMessage: 'خطای پیش‌بینی نشده در پردازش نظرات'));
      }
    });
  }
}