import 'dart:convert';

import 'package:agrilink_vocpro/core/state/result_state.dart';
import 'package:agrilink_vocpro/domain/service/app_service.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:googleapis_auth/auth_io.dart';
import 'package:http/http.dart' as http;

class AuthProvider extends ChangeNotifier {
  TextEditingController emailController = TextEditingController();
  TextEditingController passwordController = TextEditingController();

  bool _isRememberMe = false;
  bool get isRememberMe => _isRememberMe;

  String errorMessage = '';

  ResultState loginState = ResultState.initial;

  void controllerClear() {
    emailController.clear();
    passwordController.clear();
    notifyListeners();
  }

  void setRememberMe(bool value) {
    _isRememberMe = value;
    notifyListeners();
  }

  Future<void> login(context,
      {required String email, required String password}) async {
    loginState = ResultState.loading;
    notifyListeners();
    try {
      final result = await AppService().login(
        username: email,
        password: password,
        rememberMe: isRememberMe.toString(),
      );
      if (result.data != null) {
        loginState = ResultState.hasData;
        notifyListeners();
      } else {
        errorMessage = 'Login gagal, data tidak ditemukan';
        loginState = ResultState.error;
        notifyListeners();
      }
    } catch (e) {
      showDialog(
        context: context,
        builder: (BuildContext context) {
          return AlertDialog(
            title: const Text('Error'),
            content: Text('$e'),
            actions: [
              TextButton(
                child: const Text('OK'),
                onPressed: () {
                  Navigator.of(context).pop();
                },
              ),
            ],
          );
        },
      );
      loginState = ResultState.error;
      notifyListeners();
    }
  }

  bool validateInputs() {
    if (emailController.text.isEmpty || passwordController.text.isEmpty) {
      errorMessage = 'Email dan password tidak boleh kosong';
      loginState = ResultState.error;
      notifyListeners();
      return false;
    }
    return true;
  }

  Future<void> getAccessToken() async {
    try {
      final serviceAccountJson = await rootBundle.loadString(
        'assets/json/agrilink-vocpro-b37f9-firebase-adminsdk-a4f6g-e6565344e3.json',
      );

      final accountCredentials = ServiceAccountCredentials.fromJson(
        json.decode(serviceAccountJson),
      );

      const scope = ['https://www.googleapis.com/auth/firebase.messaging'];

      final client = http.Client();

      try {
        final accessCredential = await obtainAccessCredentialsViaServiceAccount(
            accountCredentials, scope, client);
        final accessToken = accessCredential.accessToken.data;
        print('Access Token: $accessToken');
      } catch (e) {
        print('Error: $e');
      }
    } catch (e) {
      print('Error 2: $e');
    }
  }
}
