import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:real_estate_mobile/features/auth/presentation/providers/auth_provider.dart';
import 'package:real_estate_mobile/features/profile/data/profile_repository.dart';

// Profile state
class ProfileState {
  final String role;
  final Map<String, dynamic> profile;
  final bool isLoading;
  final bool isSaving;
  final String? errorMessage;
  final String? successMessage;

  const ProfileState({
    this.role = 'USER',
    this.profile = const {},
    this.isLoading = true,
    this.isSaving = false,
    this.errorMessage,
    this.successMessage,
  });

  bool get isAgent => role == 'AGENT';

  ProfileState copyWith({
    String? role,
    Map<String, dynamic>? profile,
    bool? isLoading,
    bool? isSaving,
    String? errorMessage,
    String? successMessage,
    bool clearError = false,
    bool clearSuccess = false,
  }) {
    return ProfileState(
      role: role ?? this.role,
      profile: profile ?? this.profile,
      isLoading: isLoading ?? this.isLoading,
      isSaving: isSaving ?? this.isSaving,
      errorMessage: clearError ? null : (errorMessage ?? this.errorMessage),
      successMessage:
          clearSuccess ? null : (successMessage ?? this.successMessage),
    );
  }
}

class ProfileNotifier extends StateNotifier<ProfileState> {
  final ProfileRepository _repository;
  final String _role;

  ProfileNotifier(this._repository, this._role)
      : super(ProfileState(role: _role)) {
    loadProfile();
  }

  Future<void> loadProfile() async {
    state = state.copyWith(isLoading: true, clearError: true);
    try {
      final profile = await _repository.getMyProfile(_role);
      state = state.copyWith(profile: profile, isLoading: false);
    } catch (e) {
      state = state.copyWith(
        isLoading: false,
        errorMessage: e.toString(),
      );
    }
  }

  Future<void> updateProfile(Map<String, dynamic> data) async {
    state =
        state.copyWith(isSaving: true, clearError: true, clearSuccess: true);
    try {
      final updated = await _repository.updateProfile(_role, data);
      state = state.copyWith(
        profile: updated,
        isSaving: false,
        successMessage: 'Profile updated successfully',
      );
    } catch (e) {
      state = state.copyWith(
        isSaving: false,
        errorMessage: 'Failed to update profile',
      );
    }
  }
}

// Providers
final profileRepositoryProvider = Provider<ProfileRepository>((ref) {
  return ProfileRepository();
});

final profileProvider =
    StateNotifierProvider.autoDispose<ProfileNotifier, ProfileState>((ref) {
  final authState = ref.watch(authProvider);
  final role = authState.user?.role ?? 'USER';
  return ProfileNotifier(ref.watch(profileRepositoryProvider), role);
});
