import 'dart:convert';

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/presentation/store_info/bloc/store_info_state.dart';
import 'package:dio/dio.dart';

part 'store_info_event.dart';

class StoreInfoBloc extends Bloc<StoreInfoEvent, StoreInfoState> {
  final Dio _dio = Dio();
  final TokenStorageService _tokenStorage = TokenStorageService();

  StoreInfoBloc() : super(StoreInfoState()) {
    on<StoreLogoChanged>((event, emit) {
      emit(state.copyWith(logoPath: event.imagePath));
    });

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

    on<ActivityTypeChanged>((event, emit) {
      emit(state.copyWith(activityTypeId: event.activityTypeId));
    });

    on<ProvinceChanged>((event, emit) {
      emit(state.copyWith(province: event.province));
    });

    on<CityChanged>((event, emit) {
      emit(state.copyWith(city: event.city));
    });

    on<AddressChanged>((event, emit) {
      emit(state.copyWith(address: event.address));
    });

    on<PlaqueChanged>((event, emit) {
      emit(state.copyWith(plaque: event.plaque));
    });

    on<PostalCodeChanged>((event, emit) {
      emit(state.copyWith(postalCode: event.postalCode));
    });

    on<ContactPhoneChanged>((event, emit) {
      emit(state.copyWith(contactPhone: event.phone));
    });

    on<LicenseNumberChanged>((event, emit) {
      emit(state.copyWith(licenseNumber: event.license));
    });

    on<StoreLocationChanged>((event, emit) {
      emit(state.copyWith(latitude: event.latitude, longitude: event.longitude));
    });

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

    on<StoreFeatureAdded>((event, emit) {
      if (state.features.length < 3) {
        final updatedFeatures = List<String>.from(state.features)..add('');
        emit(state.copyWith(features: updatedFeatures));
      }
    });

    on<StoreFeatureRemoved>((event, emit) {
      final updatedFeatures = List<String>.from(state.features)..removeAt(event.index);
      emit(state.copyWith(features: updatedFeatures));
    });

    on<StoreFeatureUpdated>((event, emit) {
      final updatedFeatures = List<String>.from(state.features);
      if (event.index < updatedFeatures.length) {
        updatedFeatures[event.index] = event.value;
        emit(state.copyWith(features: updatedFeatures));
      }
    });

    on<SubmitStoreInfo>((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;
        }

        final schedule = state.workingDays.map((day) {
          return {
            'Day': day,
            'StartTime': state.startTime,
            'EndTime': state.endTime,
            'Status': true,
          };
        }).toList();

        final Map<String, dynamic> data = {
          'Name': state.storeName,
          'Category': state.activityTypeId,
          'Province': state.province,
          'City': state.city,
          'Address': state.address,
          'Property': jsonEncode(state.features),
          'ShopNumber': state.plaque,
          'Phone': state.contactPhone,
          'PostalCode': state.postalCode,
          'BusinessLicense': state.licenseNumber,
          'Coordinates': jsonEncode({
            'longitude': state.longitude?.toString(),
            'latitude': state.latitude?.toString(),
          }),
          'Schedule': jsonEncode(schedule),
        };

        if (state.logoPath != null && state.logoPath!.isNotEmpty) {
          data['Logo'] = await MultipartFile.fromFile(
            state.logoPath!,
            filename: state.logoPath!.split('/').last,
          );
        }

        final formData = FormData.fromMap(data);

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

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

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