import 'dart:convert';

import 'package:get/get.dart';
import 'package:encrypt_shared_preferences/provider.dart';
import 'package:http/http.dart' as http;

import 'package:f0ckapp/models/user.dart';

class AuthController extends GetxController {
  final EncryptedSharedPreferencesAsync storage =
      EncryptedSharedPreferencesAsync.getInstance();

  RxnString token = RxnString();
  Rxn<User> user = Rxn<User>();
  RxBool isLoading = false.obs;
  RxnString error = RxnString();

  @override
  void onInit() {
    super.onInit();
    loadToken();
  }

  Future<void> loadToken() async {
    token.value = await storage.getString('token');
    if (token.value != null) {
      await fetchUserInfo();
    }
  }

  Future<void> saveToken(String newToken) async {
    token.value = newToken;
    await storage.setString('token', newToken);
    await fetchUserInfo();
  }

  Future<void> logout() async {
    if (token.value != null) {
      try {
        await http.post(
          Uri.parse('https://api.f0ck.me/logout'),
          headers: {
            'Authorization': 'Bearer ${token.value}',
            'Content-Type': 'application/json',
          },
        );
      } catch (_) {}
    }
    token.value = null;
    user.value = null;
    await storage.remove('token');
  }

  Future<bool> login(String username, String password) async {
    isLoading.value = true;
    error.value = null;
    try {
      final http.Response response = await http.post(
        Uri.parse('https://api.f0ck.me/login'),
        headers: {'Content-Type': 'application/json'},
        body: json.encode({'username': username, 'password': password}),
      );
      if (response.statusCode == 200) {
        final dynamic data = json.decode(response.body);
        if (data['token'] != null) {
          await saveToken(data['token']);
          user.value = User.fromJson(data);
          return true;
        } else {
          error.value = 'Kein Token erhalten';
        }
      } else {
        error.value = 'Login fehlgeschlagen';
      }
    } catch (e) {
      error.value = e.toString();
    } finally {
      isLoading.value = false;
    }
    return false;
  }

  Future<void> fetchUserInfo() async {
    if (token.value == null) return;
    try {
      final http.Response response = await http.get(
        Uri.parse('https://api.f0ck.me/login/check'),
        headers: {'Authorization': 'Bearer ${token.value}'},
      );
      if (response.statusCode == 200) {
        final dynamic data = json.decode(response.body);
        user.value = User.fromJson(data);
      } else {
        await logout();
      }
    } catch (_) {
      await logout();
    }
  }

  bool get isLoggedIn => token.value != null && token.value!.isNotEmpty;
}
