import 'dart:convert';
import 'package:flutter/services.dart';
import 'package:get/get.dart';
import 'package:mypoint_flutter_app/networking/restful_api_client_all_request.dart';
import '../../networking/restful_api_viewmodel.dart';
import '../affiliate/model/affiliate_brand_model.dart';
import '../faqs/faqs_model.dart';
import '../voucher/models/product_model.dart';
import 'models/achievement_model.dart';
import 'models/banner_model.dart';
import 'models/brand_model.dart';
import 'models/flash_sale_model.dart';
import 'models/header_section_type.dart';
import 'models/hover_data_model.dart';
import 'models/main_section_config_model.dart';
import 'models/main_service_model.dart';
import 'models/my_product_model.dart';

class HomeTabViewModel extends RestfulApiViewModel {
  final RxList<ProductModel> products = <ProductModel>[].obs;
  final RxList<PageItemModel> news = <PageItemModel>[].obs;
  final RxList<MainServiceModel> services = <MainServiceModel>[].obs;
  final RxList<AchievementModel> achievements = <AchievementModel>[].obs;
  final RxList<BannerModel> banners = <BannerModel>[].obs;
  final RxList<BrandModel> brands = <BrandModel>[].obs;
  final RxList<AffiliateBrandModel> affiliates = <AffiliateBrandModel>[].obs;
  final RxList<MyProductModel> myProducts = <MyProductModel>[].obs;
  final RxList<MainSectionConfigModel> sectionLayouts = <MainSectionConfigModel>[].obs;
  var flashSaleData = Rxn<FlashSaleModel>();
  var hoverData = Rxn<HoverDataModel>();

  @override
  void onInit() {
    super.onInit();
    getSectionLayoutHome();
    loadDataPiPiHome();
  }

  MainSectionConfigModel? getMainSectionConfigModel(HeaderSectionType type) {
    return sectionLayouts.firstWhereOrNull((section) => section.headerSectionType == type);
  }

  Future<void> getSectionLayoutHome() async {
    showLoading();
    try {
      final response = await client.getSectionLayoutHome();
        sectionLayouts.value = response.data ?? [];
      hideLoading();
    } catch (error) {
      sectionLayouts.value = await _loadSectionLayoutHomeFromCache();
      hideLoading();
    } finally {
      if (sectionLayouts.value.isEmpty) {
        sectionLayouts.value = await _loadSectionLayoutHomeFromCache();
      }
      for (final section in sectionLayouts.value) {
        await _processSection(section);
      }
    }
  }

  Future<void> loadDataPiPiHome() async {
    try {
      final result = await client.getDataPiPiHome();
      hoverData.value = result.data;
      hoverData.refresh();
    } catch (error) {
      print("Error fetching loadDataPiPiHome: $error");
    }
  }

  Future<List<MainSectionConfigModel>> _loadSectionLayoutHomeFromCache() async {
    final jsonStr = await rootBundle.loadString('assets/data/main_layout_section_home.json');
    final List<dynamic> jsonList = json.decode(jsonStr);
    return jsonList.map((e) => MainSectionConfigModel.fromJson(e)).toList() ?? [];
  }

  Future<void> _processSection(MainSectionConfigModel section) async {
    final path = section.apiList ?? "";
    switch (section.headerSectionType) {
      case HeaderSectionType.topButton:
        final res = await client.fetchList<MainServiceModel>(
          path,
          (json) => MainServiceModel.fromJson(json as Map<String, dynamic>),
        );
        services.value = res.data ?? [];
        break;
      case HeaderSectionType.banner:
        final res = await client.fetchList<BannerModel>(
          path,
          (json) => BannerModel.fromJson(json as Map<String, dynamic>),
        );
        banners.value = res.data ?? [];
        break;
      case HeaderSectionType.campaign:
        final res = await client.fetchList<AchievementModel>(
          path,
          (json) => AchievementModel.fromJson(json as Map<String, dynamic>),
        );
        achievements.value = res.data ?? [];
        break;
      case HeaderSectionType.product:
        final res = await client.fetchList<ProductModel>(
          path,
          (json) => ProductModel.fromJson(json as Map<String, dynamic>),
        );
        products.value = res.data ?? [];
        break;
      case HeaderSectionType.news:
        final res = await client.fetchList<PageItemModel>(
          path,
          (json) => PageItemModel.fromJson(json as Map<String, dynamic>),
        );
        news.value = res.data ?? [];
        break;
      case HeaderSectionType.flashSale:
        final res = await client.fetchObject<FlashSaleModel>(
          path,
          (json) => FlashSaleModel.fromJson(json as Map<String, dynamic>),
        );
        flashSaleData.value = res.data;
        break;
      case HeaderSectionType.brand:
        final res = await client.fetchList<BrandModel>(
          path,
          (json) => BrandModel.fromJson(json as Map<String, dynamic>),
        );
        brands.value = res.data ?? [];
        break;
      case HeaderSectionType.pointPartner:
        final res = await client.fetchList<AffiliateBrandModel>(
          path,
          (json) => AffiliateBrandModel.fromJson(json as Map<String, dynamic>),
        );
        affiliates.value = (res.data ?? []).take(6).toList();
        break;
      case HeaderSectionType.myProduct:
        final res = await client.fetchList<MyProductModel>(
          path,
          (json) => MyProductModel.fromJson(json as Map<String, dynamic>),
        );
        myProducts.value = res.data ?? [];
        break;
      default:
        print("Unknown section type: ${section.headerSectionType}");
        break;
    }
  }
}