import 'package:dio/dio.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:niogu_app/core/database/app_database.dart';
import 'package:niogu_app/core/entities/custom_activity.dart';
import 'package:niogu_app/core/network/dio_client.dart';
import 'package:niogu_app/core/database/database_holder.dart';
import 'package:niogu_app/core/enums/user_role.dart';
import 'package:niogu_app/core/services/sync_services.dart';
import 'package:niogu_app/features/online_store/presentation/providers/online_store_provider.dart';
import 'package:niogu_app/features/user/presentation/providers/user_provider.dart';

final dioProvider = Provider<Dio>((ref) => DioClient().instance);

final appDatabaseProvider = Provider<AppDatabase>((ref) => database);

final syncServiceProvider = Provider<SyncService>((ref) {
  final dio = ref.watch(dioProvider);

  final appDatabase = ref.watch(appDatabaseProvider);

  return SyncService(dio, appDatabase);
});

final outletIdByOwnerProvider = StateProvider<String?>((ref) => null);

final currentOutletIdProvider = StateProvider<String?>((ref) => null);

final currentOutletNameProvider = StateProvider<String?>((ref) => null);

final currentUserIdProvider = StateProvider<String?>((ref) => null);

final currentUserNameProvider = StateProvider<String?>((ref) => null);

final currentUserEmailProvider = StateProvider<String?>((ref) => null);

final currentUserRoleProvider = StateProvider<UserRole?>((ref) => null);

final currentStatusLoginProvider = StateProvider<bool>((ref) => false);

final messageActivityStateProvider = StateProvider<MessageActivity?>(
  (ref) => null,
);

final messageActivityProvider = Provider<MessageActivity?>((ref) {
  var messageActivity = ref.watch(messageActivityStateProvider);

  final isLoggedIn = ref.watch(currentStatusLoginProvider);

  if (isLoggedIn) {
    final permissionActivityAsync = ref.watch(permissionActivityStreamProvider);

    final newOnlineOrderAsync = ref.watch(
      onlineOrderHasNotReviewStreamProvider,
    );

    if (messageActivity == null) {
      permissionActivityAsync.whenData((m) => messageActivity = m);
    }

    if (messageActivity == null) {
      newOnlineOrderAsync.whenData((m) => messageActivity = m);
    }
  }

  return messageActivity;
});
