import 'package:get/get.dart';
import 'package:mypoint_flutter_app/networking/api/notification_api.dart'
    deferred as notification_api;
import 'package:mypoint_flutter_app/networking/restful_api_client_all_request.dart';
import 'package:mypoint_flutter_app/preference/data_preference.dart';
import '../../networking/restful_api_viewmodel.dart';
import '../../preference/point/point_manager.dart';
import '../../preference/point/header_home_model.dart';
import 'models/notification_unread_model.dart';

class HeaderHomeRepository extends RestfulApiViewModel {
  HeaderHomeRepository._();
  static final HeaderHomeRepository _instance = HeaderHomeRepository._();
  factory HeaderHomeRepository() => _instance;

  final Rx<HeaderHomeModel?> _headerHome = Rx<HeaderHomeModel?>(null);
  final Rxn<NotificationUnreadData> _notificationUnread =
      Rxn<NotificationUnreadData>();
  int get totalPoint => header.totalPointActive ?? 0;

  HeaderHomeModel get header =>
      _headerHome.value ??
      HeaderHomeModel(
        greeting: 'Xin chào!',
        totalVoucher: 0,
        totalPointActive: 0,
        background: '',
      );
  Rx<HeaderHomeModel?> get headerStream => _headerHome;
  Rxn<NotificationUnreadData> get notificationStream => _notificationUnread;

  Future<void> _load({bool withLoading = false}) async {
    await Future.wait([
      fetchHeader(withLoading: withLoading),
      _fetchNotificationUnread(),
    ]);
  }

  Future<void> fetchHeader({bool withLoading = false}) async {
    if (!DataPreference.instance.logged) return;
    await callApi<HeaderHomeModel>(
      request: () => client.getDynamicHeaderHome(),
      onSuccess: (data, _) {
        _headerHome.value = data;
        UserPointManager().setPoint(data.totalPointActive ?? 0);
      },
      withLoading: withLoading,
    );
  }

  Future<void> _fetchNotificationUnread() async {
    if (!DataPreference.instance.logged) return;
    await callApi<NotificationUnreadData>(
      request: () async {
        await _ensureNotificationApiLoaded();
        final api = notification_api.NotificationApi(client);
        return api.getNotificationUnread();
      },
      onSuccess: (data, _) {
        _notificationUnread.value = data;
      },
      withLoading: false,
    );
  }

  bool _notificationApiLoaded = false;

  Future<void> _ensureNotificationApiLoaded() async {
    if (_notificationApiLoaded) return;
    await notification_api.loadLibrary();
    _notificationApiLoaded = true;
  }
}

class HeaderThemeController extends GetxController {
  final background = RxnString();
  void setBackground(String? url) => background.value = url;
}

class HeaderHomeViewModel extends GetxController {
  final HeaderHomeRepository _repository = HeaderHomeRepository();

  HeaderHomeModel get headerData => _repository.header;
  Rxn<NotificationUnreadData> get notificationUnreadData =>
      _repository.notificationStream;

  @override
  void onInit() {
    super.onInit();
    ever<HeaderHomeModel?>(_repository.headerStream, (data) {
      if (data?.background != null) {
        Get.find<HeaderThemeController>().setBackground(data?.background);
      }
    });
  }

  Future<void> freshData() => _repository._load(withLoading: false);
}
