import 'dart:async';

import 'package:flutter_riverpod/flutter_riverpod.dart';

import '../core/contracts/library.dart';
import '../core/infra/storage/home_page_cache_store.dart';
import 'di_providers.dart';
import 'session_provider.dart';

class HomeBannerNotifier extends AsyncNotifier<List<EmbyRawItem>> {
  @override
  Future<List<EmbyRawItem>> build() async {
    final session = ref.watch(activeSessionProvider);
    if (session == null) return const [];

    final store = await ref.read(homePageCacheStoreProvider.future);
    final cache = await store.readBanner(session.serverId, session.userId);

    if (cache != null) {
      unawaited(_refreshBannerFromNetwork(session.serverId, session.userId));
      return cache.bannerItems;
    }

    return _fetchAndCacheBanner(session.serverId, session.userId);
  }

  Future<List<EmbyRawItem>> _fetchAndCacheBanner(
    String serverId,
    String userId,
  ) async {
    final store = await ref.read(homePageCacheStoreProvider.future);
    final uc = await ref.read(homeBannerUseCaseProvider.future);
    final items = await uc.execute();
    unawaited(
      store.writeBanner(
        serverId,
        userId,
        HomeBannerCacheData(
          bannerItems: items,
          savedAt: DateTime.now().toUtc(),
        ),
      ),
    );
    return items;
  }

  Future<void> _refreshBannerFromNetwork(String serverId, String userId) async {
    try {
      final uc = await ref.read(homeBannerUseCaseProvider.future);
      final items = await uc.execute();

      final s = ref.read(activeSessionProvider);
      if (s == null || s.serverId != serverId || s.userId != userId) return;

      state = AsyncValue.data(items);

      final store = await ref.read(homePageCacheStoreProvider.future);
      unawaited(
        store.writeBanner(
          serverId,
          userId,
          HomeBannerCacheData(
            bannerItems: items,
            savedAt: DateTime.now().toUtc(),
          ),
        ),
      );
    } catch (_) {}
  }

  Future<void> refresh() async {
    state = const AsyncValue.loading();
    state = await AsyncValue.guard(() async {
      final session = ref.read(activeSessionProvider);
      if (session == null) return const [];
      return _fetchAndCacheBanner(session.serverId, session.userId);
    });
  }


  Future<void> softRefresh() async {
    final session = ref.read(activeSessionProvider);
    if (session == null) return;
    if (state.value == null) {
      await refresh();
      return;
    }
    await _refreshBannerFromNetwork(session.serverId, session.userId);
  }
}

final homeBannerProvider =
    AsyncNotifierProvider<HomeBannerNotifier, List<EmbyRawItem>>(
      HomeBannerNotifier.new,
    );
