import 'package:didvan/models/enums.dart';
import 'package:didvan/models/view/alert_data.dart';
import 'package:didvan/providers/core_provider.dart';
import 'package:didvan/providers/user_provider.dart';
import 'package:didvan/services/network/request.dart';
import 'package:didvan/services/network/request_helper.dart';
import 'package:didvan/utils/action_sheet.dart';

class AuthenticationState extends CoreProvier {
  int _currentPageIndex = 0;
  String username = '';
  String password = '';

  set currentPageIndex(int value) {
    _currentPageIndex = value;
    notifyListeners();
  }

  int get currentPageIndex => _currentPageIndex;

  Future<void> confirmUsername() async {
    appState = AppState.isolatedBusy;
    final RequestService service = RequestService(
      RequestHelper.confirmUsername,
      useAutherization: false,
      body: {'username': username},
    );
    await service.post();
    if (service.isSuccess && service.result['confirmed']) {
      appState = AppState.idle;
      currentPageIndex++;
    } else {
      appState = AppState.failed;
      ActionSheetUtils.showAlert(AlertData(message: service.errorMessage));
    }
  }

  Future<String?> login(UserProvider userProvider) async {
    appState = AppState.isolatedBusy;
    final RequestService service = RequestService(
      RequestHelper.login,
      useAutherization: false,
      body: {'username': username, "password": password},
    );
    await service.post();
    if (service.isSuccess && service.result['loggedIn']) {
      final token = service.result['token'];
      appState = AppState.idle;
      await userProvider.setAndGetToken(newToken: token);
      RequestService.token = token;
      await userProvider.getUserInfo();
      return token;
    } else {
      appState = AppState.failed;
      ActionSheetUtils.showAlert(AlertData(message: service.errorMessage));
    }
    return null;
  }

  Future<void> sendOtpToken() async {
    final service = RequestService(RequestHelper.otp + '?username=$username');
    await service.httpGet();
  }

  Future<bool> verifyOtpToken(String token) async {
    appState = AppState.isolatedBusy;

    final service = RequestService(RequestHelper.otp, body: {
      'code': token,
      'username': username,
    });
    await service.post();
    appState = AppState.idle;
    if (service.isSuccess) {
      currentPageIndex++;
      return true;
    }
    ActionSheetUtils.showAlert(AlertData(
      message: service.isSuccess
          ? service.result['message']
          : 'کد وارد شده صحیح نمی‌باشد',
    ));
    return false;
  }
}
