import 'package:hive_flutter/hive_flutter.dart';
import 'package:intl/intl.dart';

import '../local/models.dart';
import 'myquran_service.dart';

class ScheduleCacheStatus {
  final DateTime? startDate;
  final DateTime? endDate;
  final int cachedDays;
  final int daysUntilRefresh;

  const ScheduleCacheStatus({
    required this.startDate,
    required this.endDate,
    required this.cachedDays,
    required this.daysUntilRefresh,
  });

  const ScheduleCacheStatus.empty()
      : startDate = null,
        endDate = null,
        cachedDays = 0,
        daysUntilRefresh = -1;

  bool get hasData => startDate != null && endDate != null && cachedDays > 0;
  bool get isExpired => hasData && daysUntilRefresh < 0;
  bool get needsRefreshSoon => hasData && daysUntilRefresh <= 3;

  static ScheduleCacheStatus fromSchedules(
    Iterable<DailyPrayerSchedule> schedules,
    DateTime referenceDate,
  ) {
    DateTime? startDate;
    DateTime? endDate;
    var cachedDays = 0;

    for (final schedule in schedules) {
      final parsedDate = DateTime.tryParse(schedule.date);
      if (parsedDate == null) continue;

      final normalized = DateTime(
        parsedDate.year,
        parsedDate.month,
        parsedDate.day,
      );

      cachedDays++;
      startDate = startDate == null || normalized.isBefore(startDate)
          ? normalized
          : startDate;
      endDate = endDate == null || normalized.isAfter(endDate)
          ? normalized
          : endDate;
    }

    if (startDate == null || endDate == null || cachedDays == 0) {
      return const ScheduleCacheStatus.empty();
    }

    final today = DateTime(
      referenceDate.year,
      referenceDate.month,
      referenceDate.day,
    );

    return ScheduleCacheStatus(
      startDate: startDate,
      endDate: endDate,
      cachedDays: cachedDays,
      daysUntilRefresh: endDate.difference(today).inDays,
    );
  }
}

/// Service to sync monthly prayer data from MyQuran API → Hive.
class SyncService {
  SyncService._();
  static final SyncService instance = SyncService._();

  /// Sync current month + next month prayer data for the configured city.
  /// Returns true on success.
  Future<bool> syncMonthlyData() async {
    final settingsBox = Hive.box<AppSettings>(HiveBoxes.settings);
    final settings = settingsBox.get('default');
    if (settings == null) return false;

    final cityId = settings.cityIdApi;
    final now = DateTime.now();
    final currentMonth = DateFormat('yyyy-MM').format(now);

    // Also fetch next month for continuity
    final nextMonthDate = DateTime(now.year, now.month + 1, 1);
    final nextMonth = DateFormat('yyyy-MM').format(nextMonthDate);

    final api = MyQuranSholatService.instance;
    final scheduleBox = Hive.box<DailyPrayerSchedule>(HiveBoxes.prayerSchedule);

    var success = false;

    // Fetch current month
    final currentData = await api.getMonthlySchedule(cityId, currentMonth);
    if (currentData.isNotEmpty) {
      for (final entry in currentData.entries) {
        final jadwal = entry.value;
        scheduleBox.put(
          entry.key,
          DailyPrayerSchedule(
            date: entry.key,
            imsak: jadwal['imsak'] ?? '00:00',
            subuh: jadwal['subuh'] ?? '00:00',
            terbit: jadwal['terbit'] ?? '00:00',
            dhuha: jadwal['dhuha'] ?? '00:00',
            dzuhur: jadwal['dzuhur'] ?? '00:00',
            ashar: jadwal['ashar'] ?? '00:00',
            maghrib: jadwal['maghrib'] ?? '00:00',
            isya: jadwal['isya'] ?? '00:00',
          ),
        );
      }
      success = true;
    }

    // Fetch next month
    final nextData = await api.getMonthlySchedule(cityId, nextMonth);
    if (nextData.isNotEmpty) {
      for (final entry in nextData.entries) {
        final jadwal = entry.value;
        scheduleBox.put(
          entry.key,
          DailyPrayerSchedule(
            date: entry.key,
            imsak: jadwal['imsak'] ?? '00:00',
            subuh: jadwal['subuh'] ?? '00:00',
            terbit: jadwal['terbit'] ?? '00:00',
            dhuha: jadwal['dhuha'] ?? '00:00',
            dzuhur: jadwal['dzuhur'] ?? '00:00',
            ashar: jadwal['ashar'] ?? '00:00',
            maghrib: jadwal['maghrib'] ?? '00:00',
            isya: jadwal['isya'] ?? '00:00',
          ),
        );
      }
    }

    if (success) {
      settings.lastSyncDate = DateFormat('yyyy-MM-dd HH:mm').format(now);
      await settings.save();
    }

    return success;
  }

  /// Get today's prayer schedule from local Hive cache.
  DailyPrayerSchedule? getTodaySchedule([DateTime? targetDate]) {
    final scheduleBox =
        Hive.box<DailyPrayerSchedule>(HiveBoxes.prayerSchedule);
    final dateToFetch = targetDate ?? DateTime.now();
    final dateStr = DateFormat('yyyy-MM-dd').format(dateToFetch);
    return scheduleBox.get(dateStr);
  }

  ScheduleCacheStatus getCacheStatus([DateTime? referenceDate]) {
    final scheduleBox =
        Hive.box<DailyPrayerSchedule>(HiveBoxes.prayerSchedule);
    return ScheduleCacheStatus.fromSchedules(
      scheduleBox.values,
      referenceDate ?? DateTime.now(),
    );
  }
}
