import 'dart:io';

import 'package:dio/dio.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:flutter_secure_storage/flutter_secure_storage.dart';
import 'package:proxibuy/core/config/api_config.dart';
import 'package:proxibuy/presentation/comment/bloc/comment_event.dart';
import 'package:proxibuy/presentation/comment/bloc/comment_state.dart';
import 'package:http_parser/http_parser.dart';
import 'package:flutter/foundation.dart';

class CommentBloc extends Bloc<CommentEvent, CommentState> {
  late final Dio _dio;
  final FlutterSecureStorage _storage = const FlutterSecureStorage();

  CommentBloc() : super(CommentInitial()) {
    _dio = Dio();
    _dio.interceptors.add(
      LogInterceptor(
        requestHeader: true,
        requestBody: true,
        responseBody: true,
        responseHeader: false,
        error: true,
        logPrint: (obj) => debugPrint(obj.toString()),
      ),
    );
    on<SubmitComment>(_onSubmitComment);
  }

  Future<void> _onSubmitComment(SubmitComment event, Emitter<CommentState> emit) async {
    if (event.text.isEmpty && event.score == 0) {
        emit(const CommentSubmissionFailure("لطفا امتیاز یا نظری برای این تخفیف ثبت کنید."));
        return;
    }

    emit(CommentSubmitting());
    try {
      final token = await _storage.read(key: 'accessToken');
      if (token == null) {
        emit(const CommentSubmissionFailure("شما وارد نشده‌اید."));
        return;
      }

      final formData = FormData.fromMap({
        'Discount': event.discountId,
        'Text': event.text,
        'Score': event.score,
      });

      for (File imageFile in event.images) {
        formData.files.add(MapEntry(
          'Images',
          await MultipartFile.fromFile(
            imageFile.path,
            filename: imageFile.path.split('/').last,
            contentType: MediaType('image', 'jpeg'),
          ),
        ));
      }

      final response = await _dio.post(
        ApiConfig.baseUrl + ApiConfig.addComment,
        data: formData,
        options: Options(
          headers: {'Authorization': 'Bearer $token'},
        ),
      );

      if (response.statusCode == 200 || response.statusCode == 201) {
        emit(CommentSubmissionSuccess());
      } else {
        emit(CommentSubmissionFailure(response.data['message'] ?? 'خطا در ارسال نظر'));
      }
    } on DioException catch (e) {
      emit(CommentSubmissionFailure(e.response?.data['message'] ?? 'خطا در ارتباط با سرور'));
    } catch (e) {
      emit(CommentSubmissionFailure('خطایی ناشناخته رخ داد: $e'));
    }
  }
}