import 'package:bloc/bloc.dart';
import 'package:equatable/equatable.dart';
import 'package:tanami_app/Api_Helper/base_manager.dart';

import '../../../../Globalconst.dart';
import '../../../../core/routes/routes.dart';
import '../../../../core/utils/secure/secure_storage_service.dart';
import '../../Repository/PinAPIServices.dart';

part 'pin_event.dart';
part 'pin_state.dart';

class PinBloc extends Bloc<PinEvent, PinState> {
  final SecureStorageService secureStorageService;

  PinBloc({required this.secureStorageService})
      : super(const PinState(
            pin: '',
            pinComplete: false,
            isVerified: false,
            error: '',
            verifiedOnce: false)) {
    on<NumberPressed>((event, emit) async {
      final newPin = state.pin + event.number;

      if (newPin.length <= 6) {
        if ((event.fromscreen == "login" ||
                event.fromscreen == "LoginedInUser" ||
                event.fromscreen == "reset-pin") &&
            newPin.length < 6) {
          emit(state.copyWith(
            pin: newPin,
            pinComplete: newPin.length == 6,
            error: '',
            verifiedOnce: false,
          ));
        } else {
          if ((event.fromscreen != "login" &&
              event.fromscreen != "LoginedInUser" &&
              event.fromscreen != "reset-pin")) {
            emit(state.copyWith(
              pin: newPin,
              pinComplete: newPin.length == 6,
              error: '',
              verifiedOnce: false,
            ));
          }
        }

        if (newPin.length == 6) {
          if (event.fromscreen == "confirmpin") {
            add(VerifyPinPressed(newPin, event.fromscreen));
          } else if (event.fromscreen == "login" ||
              event.fromscreen == "LoginedInUser") {
            add(VerifyLoginPinPressed(newPin, event.fromscreen));
          } else if (event.fromscreen == "reset-pin") {
            add(UpdateLoginPinPressed(newPin, event.fromscreen));
          }
        }
      }
    });

    on<BackspacePressed>((event, emit) {
      if (state.pin.isNotEmpty) {
        final newPin = state.pin.substring(0, state.pin.length - 1);
        emit(state.copyWith(
            pin: newPin,
            pinComplete: newPin.length == 6,
            error: '',
            verifiedOnce: false));
      }
    });

    on<SavePinPressed>((event, emit) async {
      await secureStorageService.write('pin_code', state.pin);
    });

    on<VerifyPinPressed>((event, emit) async {
      emit(const PinLoading());
      final storedPin = await secureStorageService.read('pin_code');
      Map<String, dynamic> pindata = {
        "code": await secureStorageService.read("temp_token"),
        "masterPin": event.pin,
        "confirmMasterPin": event.pin,
      };
      if (storedPin == event.pin) {
        ResponseData response = await PinAPIServices().ConfirmPin(pindata);
        if (response.status == ResponseStatus.SUCCESS) {
          await secureStorageService.write(
              'accesstoken', response.data["data"]["access"]["token"]);
          await secureStorageService.write(
              'refreshtoken', response.data["data"]["refresh"]["token"]);
          await secureStorageService.write('userMPIN', storedPin.toString());
        }

        emit(state.copyWith(
            isVerified: true,
            error: '',
            verifiedOnce: true,
            pinComplete: true));
      } else {
        goRouter.pop();
        emit(state.copyWith(
          isVerified: false,
          error: Globalconst.languageSelected == "en"
              ? "Incorrect PIN. Please try again."
              : "رمز التعريف الشخصي غير صحيح",
          verifiedOnce: true,
        ));
      }
    });

    on<UpdateLoginPinPressed>((event, emit) async {
      emit(const PinLoading());
      Map<String, dynamic> pindata = {
        "masterPin": event.pin,
        "confirmMasterPin": event.pin
      };

      ResponseData response = await PinAPIServices().updatePin(pindata);
      if (response.status == ResponseStatus.SUCCESS) {
        emit(state.copyWith(
            pinComplete: true,
            pin: state.pin,
            isVerified: true,
            error: '',
            verifiedOnce: false));
      } else {
        goRouter.pop();
        emit(state.copyWith(
          pinComplete: true,
          pin: state.pin,
          isVerified: false,
          error: Globalconst.languageSelected == "en"
              ? response.message
              : "رمز التعريف الشخصي غير صحيح",
          verifiedOnce: true,
        ));
      }
    });

    on<VerifyLoginPinPressed>((event, emit) async {
      emit(const PinLoading());
      Map<String, dynamic> pindata = {
        "code": await secureStorageService.read("temp_token"),
        "masterPin": event.pin
      };

      ResponseData response = await PinAPIServices().Verifypin(pindata);
      if (response.status == ResponseStatus.SUCCESS) {
        await secureStorageService.write(
            'accesstoken', response.data["data"]["access"]["token"]);
        await secureStorageService.write(
            'refreshtoken', response.data["data"]["refresh"]["token"]);
        emit(state.copyWith(
            pinComplete: true,
            pin: state.pin,
            isVerified: true,
            error: '',
            verifiedOnce: false));
      } else {
        goRouter.pop();
        emit(state.copyWith(
          pinComplete: true,
          pin: state.pin,
          isVerified: false,
          error: Globalconst.languageSelected == "en"
              ? "Incorrect Pin Code"
              : "رمز التعريف الشخصي غير صحيح",
          verifiedOnce: true,
        ));
      }
    });
  }
}
