import 'package:get/get.dart';
import 'package:mypoint_flutter_app/app/config/constants.dart';
import 'package:mypoint_flutter_app/core/network/api/website_api.dart' deferred as website_api;
import 'package:mypoint_flutter_app/core/network/restful_api_client_all_request.dart';
import '../../core/network/restful_api_viewmodel.dart';
import 'model/campaign_detail_model.dart';
import 'model/detail_page_rule_type.dart';
import '../faqs/faqs_model.dart';

class CampaignDetailViewModel extends RestfulApiViewModel {
  var campaignDetail = Rxn<CampaignDetailResponseModel>();
  void Function(String message)? onShowAlertError;

  bool _websiteApiLoaded = false;

  Future<void> _ensureWebsiteApiLoaded() async {
    if (_websiteApiLoaded) return;
    await website_api.loadLibrary();
    _websiteApiLoaded = true;
  }

  Future<void> fetchData(DetailPageRuleType? type, String? pageId) async {
    if ((pageId ?? "").isNotEmpty) {
      await fetchWebsitePageGetDetail(pageId!);
      return;
    }
    if (type != null) {
      await fetchWebsitePage(type);
      return;
    }
    await fetchFAQItems();
  }

  Future<void> fetchFAQItems() async {
    await callApi<FAQItemModelResponse>(
      request: () async {
        await _ensureWebsiteApiLoaded();
        final api = website_api.WebsiteApi(client);
        return api.websiteFolderGetPageList({"folder_uri": "ABOUT"});
      },
      onSuccess: (data, _) async {
        final pageId = (data.items ?? []).firstWhereOrNull((item) => (item.pageId ?? "").isNotEmpty)?.pageId ?? "";
        if (pageId.isEmpty) {
          onShowAlertError?.call(Constants.commonError);
          return;
        }
        await fetchWebsitePageGetDetail(pageId);
      },
      onFailure: (msg, _, _) async {
        onShowAlertError?.call(msg);
      },
    );
  }

  Future<void> fetchWebsitePage(DetailPageRuleType type) async {
    await callApi<CampaignDetailResponseModel>(
      request: () async {
        await _ensureWebsiteApiLoaded();
        final api = website_api.WebsiteApi(client);
        return api.websitePage(type);
      },
      onSuccess: (data, _) {
        campaignDetail.value = data;
      },
      onFailure: (msg, _, _) async {
        onShowAlertError?.call(msg);
      },
    );
  }

  Future<void> fetchWebsitePageGetDetail(String pageId) async {
    await callApi<CampaignDetailResponseModel>(
      request: () async {
        await _ensureWebsiteApiLoaded();
        final api = website_api.WebsiteApi(client);
        return api.websitePageGetDetail(pageId);
      },
      onSuccess: (data, response) {
        campaignDetail.value = data;
      },
      onFailure: (msg, response, error) async {
        onShowAlertError?.call(msg);
      },
    );
  }

  Future<void> submitShareContent() async {
    final path = campaignDetail.value?.pageDetail?.clickButtonShare ?? "";
    if (path.isEmpty) return;
    await client.submitShareContent(path);
  }
}
