import 'package:hive_flutter/hive_flutter.dart';
import 'shalat_log.dart';
import 'tilawah_log.dart';
import 'dzikir_log.dart';
import 'puasa_log.dart';
import 'app_settings.dart';
import '../hive_boxes.dart';

part 'daily_worship_log.g.dart';

/// Daily worship completion log, keyed by date string 'yyyy-MM-dd'.
@HiveType(typeId: 2)
class DailyWorshipLog extends HiveObject {
  @HiveField(0)
  String date;

  @HiveField(1)
  Map<String, ShalatLog> shalatLogs; // e.g., 'subuh' -> ShalatLog

  @HiveField(5)
  TilawahLog? tilawahLog;

  @HiveField(6)
  DzikirLog? dzikirLog;

  @HiveField(7)
  PuasaLog? puasaLog;

  @HiveField(2)
  int totalItems;

  @HiveField(3)
  int completedCount;

  @HiveField(4)
  double completionPercent;

  DailyWorshipLog({
    required this.date,
    Map<String, ShalatLog>? shalatLogs,
    this.tilawahLog,
    this.dzikirLog,
    this.puasaLog,
    this.totalItems = 0,
    this.completedCount = 0,
    this.completionPercent = 0.0,
  }) : shalatLogs = shalatLogs ?? {};

  /// Dynamically calculates the "Poin Ibadah" for this day.
  int get totalPoints {
    // Return 0 points if simple mode is active
    final settingsBox = Hive.box<AppSettings>(HiveBoxes.settings);
    final isSimpleMode = settingsBox.get('default')?.simpleMode ?? false;
    if (isSimpleMode) return 0;

    int points = 0;

    // 1. Shalat Fardhu
    for (final sLog in shalatLogs.values) {
      if (sLog.completed) {
        if (sLog.location == 'Masjid') {
          points += 25;
        } else {
          points += 10;
        }
      }
      if (sLog.qabliyah == true) points += 5;
      if (sLog.badiyah == true) points += 5;
    }

    // 2. Tilawah
    if (tilawahLog != null) {
      // 1 point per Ayat read
      points += tilawahLog!.rawAyatRead;
      
      // Bonus 20 points for completing daily target
      if (tilawahLog!.isCompleted) {
        points += 20;
      }
    }

    // 3. Dzikir & Puasa
    if (dzikirLog != null) {
      if (dzikirLog!.pagi) points += 10;
      if (dzikirLog!.petang) points += 10;
    }
    if (puasaLog != null && puasaLog!.completed) {
      points += 30;
    }

    return points;
  }
}
