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/core/gen/assets.gen.dart';
import 'package:proxibuy/domain/entities/category_entity.dart';
import 'notification_preferences_event.dart';
import 'notification_preferences_state.dart';

class NotificationPreferencesBloc
    extends Bloc<NotificationPreferencesEvent, NotificationPreferencesState> {
  final Dio _dio = Dio();
  final FlutterSecureStorage _storage = const FlutterSecureStorage();

  NotificationPreferencesBloc() : super(const NotificationPreferencesState()) {
    on<LoadCategories>(_onLoadCategories);
    on<ToggleCategorySelection>(_onToggleCategorySelection);
    on<SubmitPreferences>(_onSubmitPreferences);
    on<LoadFavoriteCategories>(_onLoadFavoriteCategories);

    add(LoadCategories());
  }

  void _onLoadCategories(
      LoadCategories event, Emitter<NotificationPreferencesState> emit) {
    final categories = [
      CategoryEntity(id: "e33dd7f9-5b20-4273-8eea-59da6ca5f206", name: 'لوازم دیجیتال', icon: Assets.icons.digital),
      CategoryEntity(id: "b73a868a-a2d2-4d96-8fd4-615327ed9629", name: 'کافی‌شاپ', icon: Assets.icons.coffeeshop),
      CategoryEntity(id: "b5881239-bfd5-4c27-967a-187316a7e0b7", name: 'رستوران', icon: Assets.icons.resturan),
      CategoryEntity(id: "6803b940-3e19-48cd-9190-28d9f25421ff", name: 'فست‌فود', icon: Assets.icons.fastfood),
      CategoryEntity(id: "71e371f8-a47a-4a58-aee6-4ed0f26bf29b", name: 'پوشاک', icon: Assets.icons.pooshak),
      CategoryEntity(id: "42acff41-1165-4e62-89b9-58db7329ec3a", name: 'تریا', icon: Assets.icons.teria),
      CategoryEntity(id: "2f38918c-5566-4aec-a0a9-2c7c48b1e878", name: 'کیف‌وکفش', icon: Assets.icons.kafsh),
      CategoryEntity(id: "52c51010-3a63-4264-a350-e011c889f3dd", name: 'سینما', icon: Assets.icons.cinama),
      CategoryEntity(id: "34185954-f79f-4b9e-8eb2-1702679c40a0", name: 'لوازم آرایشی', icon: Assets.icons.arayesh),
      CategoryEntity(id: "e4517b0c-aacf-4758-94bd-85f45062980f", name: 'طلا و زیورآلات', icon: Assets.icons.tala),
    ];
    emit(state.copyWith(categories: categories));
  }

  void _onToggleCategorySelection(
      ToggleCategorySelection event, Emitter<NotificationPreferencesState> emit) {
    final selectedIds = Set<String>.from(state.selectedCategoryIds);
    if (selectedIds.contains(event.categoryId)) {
      selectedIds.remove(event.categoryId);
    } else {
      selectedIds.add(event.categoryId);
    }
    emit(state.copyWith(selectedCategoryIds: selectedIds));
  }

  Future<void> _onSubmitPreferences(
      SubmitPreferences event, Emitter<NotificationPreferencesState> emit) async {
    emit(state.copyWith(isLoading: true, errorMessage: null, submissionSuccess: false));
    try {
      final token = await _storage.read(key: 'accessToken');
      if (token == null) {
        if (isClosed) return; //  بررسی قبل از emit
        emit(state.copyWith(isLoading: false, errorMessage: "شما وارد نشده‌اید."));
        return;
      }

      final response = await _dio.post(
        ApiConfig.baseUrl + ApiConfig.updateCategories,
        data: {"FCategory": state.selectedCategoryIds.toList()},
        options: Options(headers: {'Authorization': 'Bearer $token'}),
      );

      if (isClosed) return; //  بررسی قبل از emit

      if (response.statusCode == 200) {
        emit(state.copyWith(isLoading: false, submissionSuccess: true));
      } else {
        emit(state.copyWith(
            isLoading: false,
            errorMessage: response.data['message'] ?? 'خطا در ثبت اطلاعات'));
      }
    } on DioException catch (e) {
      if (isClosed) return; //  بررسی قبل از emit
      emit(state.copyWith(
          isLoading: false,
          errorMessage: e.response?.data['message'] ?? 'خطا در ارتباط با سرور'));
    }
  }

  Future<void> _onLoadFavoriteCategories(
      LoadFavoriteCategories event, Emitter<NotificationPreferencesState> emit) async {
    emit(state.copyWith(isLoading: true, errorMessage: null));
    try {
      final token = await _storage.read(key: 'accessToken');
      if (token == null) {
        if (isClosed) return; //  بررسی قبل از emit
        emit(state.copyWith(isLoading: false, errorMessage: "شما وارد نشده‌اید."));
        return;
      }

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

      if (isClosed) return; //  بررسی قبل از emit

      if (response.statusCode == 200) {
        final List<dynamic> fCategory = response.data['data']['FCategory'];
        final Set<String> favoriteCategoryIds =
            fCategory.map((category) => category['ID'] as String).toSet();
        emit(state.copyWith(
          selectedCategoryIds: favoriteCategoryIds,
          isLoading: false,
        ));
      } else {
        emit(state.copyWith(
            isLoading: false,
            errorMessage: response.data['message'] ?? 'خطا در دریافت اطلاعات'));
      }
    } on DioException catch (e) {
      if (isClosed) return; //  بررسی قبل از emit
      emit(state.copyWith(
          isLoading: false,
          errorMessage: e.response?.data['message'] ?? 'خطا در ارتباط با سرور'));
    }
  }
}