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:dio/dio.dart';
import 'package:business_panel/core/utils/logging_interceptor.dart';
part 'auth_event.dart';
part 'auth_state.dart';

class AuthBloc extends Bloc<AuthEvent, AuthState> {
  late final Dio _dio;
  final TokenStorageService _tokenStorage = TokenStorageService();

  AuthBloc() : super(AuthInitial()) {
    _dio = Dio();
    _dio.interceptors.add(LoggingInterceptor());

    on<CheckAuthStatus>((event, emit) async {
      emit(AuthLoading());
      final token = await _tokenStorage.getAccessToken();
      emit(AuthChecked(token != null && token.isNotEmpty));
    });

    on<CheckShopStatus>((event, emit) async {
      emit(AuthLoading());
      try {
        final token = await _tokenStorage.getAccessToken();
        if (token == null || token.isEmpty) {
          emit(AuthFailure("Token not found. Please log in again."));
          return;
        }

        // Use the ApiConfig class
        await _dio.get(
          ApiConfig.checkShopStatus, // <-- تغییر در این خط
          options: Options(
            headers: {'Authorization': 'Bearer $token'},
          ),
        );
        
        emit(ShopExists());

      } on DioException catch (e) {
        if (e.response?.statusCode == 404) {
          emit(NoShop());
        } else {
          emit(AuthFailure(e.response?.data?['message'] ?? 'An error occurred while checking shop status.'));
        }
      } catch (e) {
        emit(AuthFailure('An unexpected error occurred: ${e.toString()}'));
      }
    });

    on<SendOTPEvent>((event, emit) async {
      emit(AuthLoading());
      try {
        // Use the ApiConfig class
        final response = await _dio.post(
          ApiConfig.sendOtp, // <-- تغییر در این خط
          data: {'Phone': event.phoneNumber, 'Code': event.countryCode},
        );

        if (response.statusCode == 200) {
          emit(AuthCodeSentSuccess());
        } else {
          emit(AuthFailure(response.data['message'] ?? 'An error occurred.'));
        }
      } on DioException catch (e) {
        emit(AuthFailure(e.response?.data['message'] ?? 'Network error.'));
      }
    });

    on<VerifyOTPEvent>((event, emit) async {
      emit(AuthLoading());
      try {
        // Use the ApiConfig class
        final response = await _dio.post(
          ApiConfig.verifyOtp, // <-- تغییر در این خط
          data: {
            'Phone': event.phoneNumber,
            'Code': event.countryCode,
            'OTP': event.otp,
          },
        );

        if (response.statusCode == 200 && response.data['data']['accessToken'] != null) {
          final accessToken = response.data['data']['accessToken'];
          final refreshToken = response.data['data']['refreshToken'];

          await _tokenStorage.saveTokens(
            accessToken: accessToken,
            refreshToken: refreshToken,
          );

          add(CheckShopStatus());

        } else {
          emit(AuthFailure(response.data['message'] ?? 'The verification code is incorrect.'));
        }
      } on DioException catch (e) {
        emit(AuthFailure(e.response?.data['message'] ?? 'Network error.'));
      }
    });
  }
}