import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:real_estate_mobile/features/home/data/home_repository.dart';
import 'package:real_estate_mobile/features/home/data/models/landing_page_content.dart';

final homeRepositoryProvider = Provider<HomeRepository>((ref) {
  return HomeRepository();
});

class HomeState {
  final LandingPageContent? content;
  final bool isLoading;
  final String? error;

  const HomeState({
    this.content,
    this.isLoading = false,
    this.error,
  });

  HomeState copyWith({
    LandingPageContent? content,
    bool? isLoading,
    String? error,
  }) {
    return HomeState(
      content: content ?? this.content,
      isLoading: isLoading ?? this.isLoading,
      error: error,
    );
  }
}

class HomeNotifier extends StateNotifier<HomeState> {
  final HomeRepository _repository;

  HomeNotifier(this._repository) : super(const HomeState()) {
    loadContent();
  }

  Future<void> loadContent() async {
    state = state.copyWith(isLoading: true, error: null);

    try {
      final content = await _repository.getLandingPageContent();
      state = state.copyWith(content: content, isLoading: false);
    } catch (e) {
      state = state.copyWith(
        isLoading: false,
        error: 'Failed to load content',
      );
    }
  }
}

final homeProvider = StateNotifierProvider<HomeNotifier, HomeState>((ref) {
  final repository = ref.watch(homeRepositoryProvider);
  return HomeNotifier(repository);
});
