import 'dart:io';

import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:local_auth/local_auth.dart';
import 'package:tanami_app/Globalconst.dart';
import 'package:tanami_app/core/utils/secure/secure_storage_service.dart';
import 'package:tanami_app/features/biometric/domain/repository/biometric_api.dart';

import '../../../Api_Helper/base_manager.dart';
import '../../../core/utils/device_info/device_info_data.dart';
import 'biometric_event.dart';
import 'biometric_state.dart';

class BiometricBloc extends Bloc<BiometricEvent, BiometricState> {
  final LocalAuthentication localAuthentication;
  final SecureStorageService secureStorageService;

  BiometricBloc(this.localAuthentication, this.secureStorageService)
      : super(BiometricInitial()) {
    on<CheckBiometricEvent>(_onCheckBiometric);
    on<AuthenticateBiometricEvent>(_onAuthenticateBiometric);
  }

  Future<void> _onCheckBiometric(
      CheckBiometricEvent event, Emitter<BiometricState> emit) async {
    emit(BiometricChecking());
    bool canAuthenticate = await localAuthentication.canCheckBiometrics;
    emit(BiometricChecked(canAuthenticate));
  }

  Future<void> _onAuthenticateBiometric(
      AuthenticateBiometricEvent event, Emitter<BiometricState> emit) async {
    emit(BiometricAuthenticating());
    try {
      bool authenticated = false;
      if (Platform.isIOS) {
        authenticated = await localAuthentication.authenticate(
          localizedReason: Globalconst.languageSelected == "en"
              ? 'Please authenticate to access the app'
              : 'يرجى المصادقة للوصول إلى التطبيق',
          options: const AuthenticationOptions(
            useErrorDialogs: true,
            stickyAuth: true,
            biometricOnly: true,
          ),
        );
      } else if (Platform.isAndroid) {
        authenticated = await localAuthentication.authenticate(
          localizedReason: Globalconst.languageSelected == "en"
              ? 'Please authenticate to access the app'
              : 'يرجى المصادقة للوصول إلى التطبيق',
          options: const AuthenticationOptions(
            useErrorDialogs: true,
            stickyAuth: true,
          ),
        );
      }

      if (authenticated) {
        Map<String, dynamic> biometricLoginData = {
          "code": await secureStorageService.read("temp_token"),
          "deviceId": await DeviceInfoData().getDeviceId(),
        };

        ResponseData response =
            await BiometricAPIServices().biometricLoginApi(biometricLoginData);
        if (response.status == ResponseStatus.SUCCESS) {
          await secureStorageService.write(
              'accesstoken', response.data["data"]["access"]["token"]);
          await secureStorageService.write(
              'refreshtoken', response.data["data"]["refresh"]["token"]);
          emit(BiometricAuthenticated());
        } else {
          if (Globalconst.languageSelected == "en") {
            emit(BiometricFailed('Authentication failed'));
          } else {
            emit(BiometricFailed('المصادقة فشلت'));
          }
        }
      } else {
        if (Globalconst.languageSelected == "en") {
          emit(BiometricFailed('Authentication failed'));
        } else {
          emit(BiometricFailed('المصادقة فشلت'));
        }
      }
    } catch (e) {
      emit(BiometricFailed(e.toString()));
    }
  }
}
