import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import '../models/user_profile.dart';
import '../models/preferences.dart';
import '../models/decision_log.dart';
import 'auth_service.dart';

class FirestoreService {
  final FirebaseFirestore _db = FirebaseFirestore.instance;
  final String? uid;

  FirestoreService(this.uid);

  // User Profile
  Future<UserProfile?> getUserProfile() async {
    if (uid == null) return null;
    final doc = await _db.collection('users').doc(uid).get();
    if (doc.exists && doc.data() != null) {
      return UserProfile.fromMap(doc.data()!, uid!);
    }
    return null;
  }

  Stream<UserProfile?> streamUserProfile() {
    if (uid == null) return Stream.value(null);
    return _db.collection('users').doc(uid).snapshots().map((doc) {
      if (doc.exists && doc.data() != null) {
        return UserProfile.fromMap(doc.data()!, uid!);
      }
      return null;
    });
  }

  Future<void> saveUserProfile(UserProfile profile) async {
    if (uid == null) return;
    await _db
        .collection('users')
        .doc(uid)
        .set(profile.toMap(), SetOptions(merge: true));
  }

  // Preferences
  Stream<AppPreferences> streamPreferences() {
    if (uid == null) return Stream.value(AppPreferences());
    return _db
        .collection('users')
        .doc(uid)
        .collection('settings')
        .doc('preferences')
        .snapshots()
        .map((doc) {
          if (doc.exists && doc.data() != null) {
            return AppPreferences.fromMap(doc.data()!);
          }
          return AppPreferences(); // Default
        });
  }

  Future<void> savePreferences(AppPreferences prefs) async {
    if (uid == null) return;
    await _db
        .collection('users')
        .doc(uid)
        .collection('settings')
        .doc('preferences')
        .set(prefs.toMap(), SetOptions(merge: true));
  }

  // Decision Logs
  Stream<List<DecisionLog>> streamDecisionLogs() {
    if (uid == null) return Stream.value([]);
    return _db
        .collection('users')
        .doc(uid)
        .collection('decision_logs')
        .orderBy('createdAt', descending: true)
        .limit(20)
        .snapshots()
        .map((snapshot) {
          return snapshot.docs
              .map((doc) => DecisionLog.fromMap(doc.data(), doc.id))
              .toList();
        });
  }

  Future<void> logDecision(DecisionLog log) async {
    if (uid == null) return;
    await _db
        .collection('users')
        .doc(uid)
        .collection('decision_logs')
        .doc(log.id)
        .set(log.toMap());
  }

  Future<void> updateDecisionAction(String logId, String actionKey) async {
    if (uid == null) return;
    await _db
        .collection('users')
        .doc(uid)
        .collection('decision_logs')
        .doc(logId)
        .update({'chosenAction': actionKey});
  }
}

final firestoreServiceProvider = Provider<FirestoreService>((ref) {
  final user = ref.watch(authStateProvider).value;
  return FirestoreService(user?.uid);
});

final userProfileProvider = StreamProvider<UserProfile?>((ref) {
  final service = ref.watch(firestoreServiceProvider);
  return service.streamUserProfile();
});

final preferencesProvider = StreamProvider<AppPreferences>((ref) {
  final service = ref.watch(firestoreServiceProvider);
  return service.streamPreferences();
});

// Alias for backwards compatibility
final appPreferencesProvider = preferencesProvider;

final decisionLogsProvider = StreamProvider<List<DecisionLog>>((ref) {
  final service = ref.watch(firestoreServiceProvider);
  return service.streamDecisionLogs();
});
