import 'package:business_panel/core/config/api_config.dart';
import 'package:business_panel/core/services/token_storage_service.dart';
import 'package:dio/dio.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:intl/intl.dart';
import 'discount_event.dart';
import 'discount_state.dart';

class DiscountBloc extends Bloc<DiscountEvent, DiscountState> {
  DiscountBloc() : super(const DiscountState()) {
    
    final Dio _dio = Dio();
    final TokenStorageService _tokenStorage = TokenStorageService();

    on<ProductImageAdded>((event, emit) {
      List<String> updatedImages = List.from(state.productImages);
      if (updatedImages.length > event.index) {
        updatedImages[event.index] = event.imagePath;
      } else {
        updatedImages.add(event.imagePath);
      }
      emit(state.copyWith(productImages: updatedImages));
    });

    on<ProductNameChanged>((event, emit) {
      emit(state.copyWith(productName: event.name));
    });

    on<DiscountTypeChanged>((event, emit) {
      emit(state.copyWith(discountTypeId: event.typeId));
    });

    on<DescriptionChanged>((event, emit) {
      emit(state.copyWith(description: event.description));
    });

    on<ValidityDateChanged>((event, emit) {
      emit(state.copyWith(startDate: event.startDate, endDate: event.endDate));
    });

    on<TimeRangeChanged>((event, emit) {
      emit(state.copyWith(startTime: event.startTime, endTime: event.endTime));
    });

    on<PriceChanged>((event, emit) {
      emit(state.copyWith(price: event.price));
    });

    on<DiscountedPriceChanged>((event, emit) {
      emit(state.copyWith(discountedPrice: event.price));
    });

    on<NotificationRadiusChanged>((event, emit) {
      emit(state.copyWith(notificationRadius: event.radius));
    });

    on<SubmitDiscount>((event, emit) async {
      emit(state.copyWith(isSubmitting: true, errorMessage: null));

      try {
        final token = await _tokenStorage.getAccessToken();
        if (token == null) {
          emit(state.copyWith(isSubmitting: false, errorMessage: "خطای احراز هویت."));
          return;
        }

        List<MultipartFile> imageFiles = [];
        for (var imagePath in state.productImages) {
          imageFiles.add(await MultipartFile.fromFile(
            imagePath,
            filename: imagePath.split('/').last,
          ));
        }

        final data = {
          'Name' : state.productName,
          'Images': imageFiles,
          'Type': state.discountTypeId,
          'Description': state.description,
          'Price': double.tryParse(state.price),
          'NPrice': double.tryParse(state.discountedPrice),
          'Start': state.startDate != null ? DateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'").format(state.startDate!) : null,
          'End': state.endDate != null ? DateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'").format(state.endDate!) : null,
          'StartTime': state.startTime,
          'EndTime': state.endTime,
          'Radius': state.notificationRadius,
        };

        final formData = FormData.fromMap(data);

        await _dio.post(
          ApiConfig.addDiscount,
          data: formData,
          options: Options(
            headers: {'Authorization': 'Bearer $token'},
          ),
        );

        emit(state.copyWith(isSubmitting: false, isSuccess: true));

      } on DioException catch (e) {
        emit(state.copyWith(
          isSubmitting: false,
          errorMessage: e.response?.data['message'] ?? 'خطای سرور.',
        ));
      } catch (e) {
        emit(state.copyWith(isSubmitting: false, errorMessage: 'خطای ناشناخته: ${e.toString()}'));
      }
    });
  }
}
