import 'dart:developer';

import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:softplayer_web/core/api/v1/public_accounts.dart';
import 'package:softplayer_web/core/tokens/application/tokens_application.dart';
import 'package:softplayer_web/features/authorization/application/sign_in_data.dart';
import 'package:softplayer_web/features/authorization/application/sign_up_data.dart';

class AuthState {
  final bool isAuthorized;

  const AuthState({this.isAuthorized = false});
  AuthState copyWith({bool? isAuthorized}) {
    return AuthState(isAuthorized: isAuthorized ?? this.isAuthorized);
  }
}

final authorizationControllerProvider =
    AsyncNotifierProvider<AuthorizationController, AuthState>(
      AuthorizationController.new,
    );

class AuthorizationController extends AsyncNotifier<AuthState> {
  @override
  Future<AuthState> build() async {
    final tokenState = await ref.watch(tokensControllerProvider.future);
    if (tokenState.getAccessToken().isEmpty &&
        tokenState.getRefreshToken().isNotEmpty) {
      final tokenCtrl = ref.read(tokensControllerProvider.notifier);
      await tokenCtrl.checkTokens();
    }
    final isAuthorized =
        tokenState.getAccessToken().isNotEmpty &&
        tokenState.getRefreshToken().isNotEmpty;
    return AuthState(isAuthorized: isAuthorized);
  }

  Future<void> signin(SignInData form) async {
    state = const AsyncLoading();

    state = await AsyncValue.guard(() async {
      final accountsGrpc = ref.read(publicAccountsGrpcProvider);
      final tokenCtrl = ref.read(tokensControllerProvider.notifier);

      try {
        final response = await accountsGrpc.signIn(form.toProto());
        await tokenCtrl.writeTokenPair(Tokens.fromProto(response.tokenPair));
        return state.value!.copyWith(isAuthorized: true);
      } catch (e) {
        rethrow;
      }
    });
  }

  Future<void> signup(SignUpData form) async {
    state = const AsyncLoading();

    state = await AsyncValue.guard(() async {
      final accountsGrpc = ref.read(publicAccountsGrpcProvider);
      final tokenCtrl = ref.read(tokensControllerProvider.notifier);

      final response = await accountsGrpc.signUp(form.toProto());
      await tokenCtrl.writeTokenPair(Tokens.fromProto(response.tokenPair));
      return state.value!.copyWith(isAuthorized: true);
    });
  }

  Future<void> logout() async {
    state = await AsyncValue.guard(() async {
      return state.value!.copyWith(isAuthorized: false);
    });
  }
}
