import 'package:flutter/foundation.dart';
import 'package:shared_preferences/shared_preferences.dart';
import '../services/firebase_service.dart';

class DailyCheckinService {
  static final DailyCheckinService _instance = DailyCheckinService._internal();
  factory DailyCheckinService() => _instance;
  DailyCheckinService._internal();

  static const String _lastCheckinKey = 'checkin_last_date_';

  // ── Check if user needs to do daily check-in today ──────────────────────
  Future<bool> shouldShowCheckin(String userId) async {
    try {
      final userData = await FirebaseService().getUserData(userId);
      if (userData == null) return false;

      final lastCheckin = userData.lastCheckinDate;
      final now = DateTime.now();

      if (lastCheckin == null) return true;

      final isSameDay =
          lastCheckin.year == now.year &&
          lastCheckin.month == now.month &&
          lastCheckin.day == now.day;

      return !isSameDay;
    } catch (e) {
      debugPrint('Error checking daily check-in status: $e');
      return false;
    }
  }

  // ── Save daily preferences to Firestore ─────────────────────────────────
  Future<void> saveDailyPreferences(
    String userId,
    Map<String, dynamic> preferences,
  ) async {
    try {
      final userData = await FirebaseService().getUserData(userId);
      if (userData == null) throw Exception('User not found');

      // ── Sinkronkan keinginan harian → favoriteCategories di profil ─────────
      // Agar preferensi profil selalu selaras dengan keinginan harian user
      final String keinginan = (preferences['keinginan'] as String?) ?? '';
      List<String> updatedFavCategories =
          List<String>.from(userData.preferences.favoriteCategories);

      if (keinginan == 'minuman') {
        // Hapus semua kategori makanan, pertahankan kategori minuman
        updatedFavCategories.removeWhere((c) =>
            c.toLowerCase().contains('makanan') ||
            c.toLowerCase().contains('snack') ||
            c.toLowerCase().contains('dessert') ||
            c.toLowerCase().contains('pastry') ||
            c.toLowerCase().contains('sarapan') ||
            c.toLowerCase().contains('berkuah'));
        // Tambahkan Minuman Dingin & Minuman Panas jika belum ada
        if (!updatedFavCategories.any((c) => c.toLowerCase().contains('minuman'))) {
          updatedFavCategories.add('Minuman Dingin');
        }
      } else if (keinginan == 'makanan') {
        // Hapus semua kategori minuman, pertahankan kategori makanan
        updatedFavCategories.removeWhere((c) =>
            c.toLowerCase().contains('minuman'));
        // Tambahkan Makanan Berat jika kosong
        if (updatedFavCategories.isEmpty) {
          updatedFavCategories.add('Makanan Berat');
        }
      }
      // Jika 'keduanya', tidak ada perubahan pada favoriteCategories

      final updatedPreferences = userData.preferences.copyWith(
        favoriteCategories: updatedFavCategories,
      );

      final updatedUser = userData.copyWith(
        lastCheckinDate: DateTime.now(),
        dailyPreferences: preferences,
        preferences: updatedPreferences,
      );

      await FirebaseService().updateUserData(updatedUser);

      // also cache locally so shouldShowCheckin is fast next call
      final prefs = await SharedPreferences.getInstance();
      await prefs.setString(
        '$_lastCheckinKey$userId',
        DateTime.now().toIso8601String(),
      );

      debugPrint('✅ Daily preferences saved successfully');
      debugPrint('✅ favoriteCategories updated to: $updatedFavCategories');
    } catch (e) {
      debugPrint('❌ Error saving daily preferences: $e');
      rethrow;
    }
  }

  // ── Clear local cache ────────────────────────────────────────────────────
  Future<void> clearCache(String userId) async {
    try {
      final prefs = await SharedPreferences.getInstance();
      await prefs.remove('$_lastCheckinKey$userId');
    } catch (e) {
      debugPrint('❌ Error clearing cache: $e');
    }
  }
}
