import 'package:autos/data/repositories/brands_repository_impl.dart';
import 'package:autos/data/sources/remote/api_service.dart';
import 'package:autos/domain/entities/brands.dart';
import 'package:autos/presentation/providers/user_provider.dart';
import 'package:flutter/widgets.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:flutter_riverpod/legacy.dart';

/// ✅ API Service Provider
final brandsApiServiceProvider = Provider<ApiService>((ref) => ApiService());

/// ✅ Repository Provider
final brandsRepositoryProvider = Provider<BrandsRepositoryImpl>(
  (ref) => BrandsRepositoryImpl(ref.read(brandsApiServiceProvider)),
);

/// ✅ Brands Notifier
class BrandsNotifier extends StateNotifier<AsyncValue<List<BrandEntity>>> {
  final BrandsRepositoryImpl repository;
  final Ref ref;

  BrandsNotifier(this.repository, this.ref) : super(const AsyncValue.loading());

  /// Fetch brands every time page opens
 Future<void> fetchBrands() async {
  state = const AsyncValue.loading();

  try {
    ///  READ USER DIRECTLY FROM userProvider (NOT userDetailsProvider)
    final userAsync = ref.read(userProvider);

    final user = userAsync.value;

    if (user == null || user.id.isEmpty) {
      throw Exception("User id is empty");
    }

    debugPrint("✅ FETCHING BRANDS FOR USER ID: ${user.id}");

    final brands = await repository.getBrands();

    state = AsyncValue.data(brands);
  } catch (e, st) {
    state = AsyncValue.error(e, st);
    debugPrint("❌ Brands fetch error: $e");
  }
}


  /// SAVE SELECTED BRANDS TO SERVER (Bulk Insert)
Future<void> saveSelectedBrands(List<BrandEntity> selectedBrands) async {
  try {
    final userAsync = ref.read(userProvider);
    final user = userAsync.value;

    if (user == null) throw Exception("User not logged in");

    final response = await repository.saveSelectedBrands(
      userId: user.id,
      brands: selectedBrands,
    );

    debugPrint("✅ Save Success: ${response["message"]}");
  } catch (e) {
    debugPrint("❌ Save Error: $e");
    rethrow;
  }
}

}

/// Brands State Provider
final brandsProvider =
    StateNotifierProvider<BrandsNotifier, AsyncValue<List<BrandEntity>>>(
  (ref) {
    final repo = ref.read(brandsRepositoryProvider);
    return BrandsNotifier(repo, ref);
  },
);
