import 'package:flutter/foundation.dart';
import 'package:firebase_database/firebase_database.dart';
import '../providers/panen_provider.dart';
import '../providers/kandang_provider.dart';
import 'notification_service.dart';

/// Service untuk menghubungkan PanenScheduler dengan PanenProvider
/// Bertanggung jawab untuk trigger capture otomatis
class PanenAutoCaptureService {
  static final FirebaseDatabase _database = FirebaseDatabase.instance;

  static String _fallbackKandangName(String kandangId) {
    if (kandangId == 'kandang_1') return 'Kandang 1';
    if (kandangId == 'kandang_2') return 'Kandang 2';
    return kandangId;
  }

  static String _displayNameForNotification(String kandangId, String name) {
    final lower = kandangId.toLowerCase();
    if (lower == 'kandang_1' || lower == 'kandang1') return 'kandang 1';
    if (lower == 'kandang_2' || lower == 'kandang2') return 'kandang 2';
    return name.toLowerCase();
  }

  /// Trigger capture panen pagi (biasanya dipanggil scheduler jam 09:00)
  /// Membaca sensor value untuk SETIAP kandang dan trigger capture
  static Future<void> triggerMorningCapture(
    PanenProvider panenProvider,
    KandangProvider kandangProvider,
  ) async {
    try {
      if (kDebugMode) {
        print('🟢 Triggering Morning Panen Capture');
      }

      // Baca sensor data dari Firebase
      final dataRef = _database.ref('data');
      final snapshot = await dataRef.get();

      if (snapshot.exists) {
        final data = Map<dynamic, dynamic>.from(snapshot.value as Map);

        // Mapping kandang ke sensor
        // Sesuaikan dengan struktur firebase kamu
        final sensorMap = {
          'kandang_1': data['infra1'] ?? 0,
          'kandang_2': data['infra2'] ?? 0,
          // Tambah kandang lain sesuai kebutuhan
        };

        final capturedTotals = <String, int>{};

        // Trigger capture untuk setiap kandang
        for (final entry in sensorMap.entries) {
          final kandangId = entry.key;
          final sensorValue = entry.value;

          // Get kandang nama dari KandangProvider
          try {
            final matched = kandangProvider.kandangs
                .where((k) => k.id == kandangId)
                .toList();
            final kandangNama = matched.isNotEmpty
                ? matched.first.nama
                : _fallbackKandangName(kandangId);

            final panen = await panenProvider.captureScheduledPanenPagi(
              kandangId,
              kandangNama,
              sensorValue as int,
            );

            if (panen != null) {
              capturedTotals[
                      _displayNameForNotification(kandangId, kandangNama)] =
                  panen.jumlahTelur;
            }
          } catch (e) {
            if (kDebugMode) {
              print('⚠️ Kandang $kandangId tidak found: $e');
            }
          }
        }

        if (capturedTotals.isNotEmpty) {
          await NotificationService.instance.showPanenSummaryNotification(
            jenisPanen: 'pagi',
            kandangTotals: capturedTotals,
          );
        }

        if (kDebugMode) {
          print('✅ Morning capture triggered for all kandang');
        }
      }
    } catch (e) {
      if (kDebugMode) {
        print('❌ Error in triggerMorningCapture: $e');
      }
    }
  }

  /// Trigger capture panen sore (biasanya dipanggil scheduler jam sore)
  /// Membaca sensor value untuk SETIAP kandang dan hitung delta
  /// Setelah panen sore selesai, hasil akan otomatis direset
  static Future<void> triggerAfternoonCapture(
    PanenProvider panenProvider,
    KandangProvider kandangProvider, {
    bool isLastSchedule = false,
  }) async {
    try {
      if (kDebugMode) {
        print(
            '🟡 Triggering Afternoon Panen Capture (isLastSchedule=$isLastSchedule)');
      }

      // Baca sensor data dari Firebase
      final dataRef = _database.ref('data');
      final snapshot = await dataRef.get();

      if (snapshot.exists) {
        final data = Map<dynamic, dynamic>.from(snapshot.value as Map);

        // Mapping kandang ke sensor
        final sensorMap = {
          'kandang_1': data['infra1'] ?? 0,
          'kandang_2': data['infra2'] ?? 0,
          // Tambah kandang lain sesuai kebutuhan
        };

        final capturedTotals = <String, int>{};

        // Trigger capture untuk setiap kandang (dengan delta)
        for (final entry in sensorMap.entries) {
          final kandangId = entry.key;
          final sensorValue = entry.value;

          // Get kandang nama dari KandangProvider
          try {
            final matched = kandangProvider.kandangs
                .where((k) => k.id == kandangId)
                .toList();
            final kandangNama = matched.isNotEmpty
                ? matched.first.nama
                : _fallbackKandangName(kandangId);

            final panen = await panenProvider.captureScheduledPanenSore(
              kandangId,
              kandangNama,
              sensorValue as int,
            );

            if (panen != null) {
              capturedTotals[
                      _displayNameForNotification(kandangId, kandangNama)] =
                  panen.jumlahTelur;
            }
          } catch (e) {
            if (kDebugMode) {
              print('⚠️ Kandang $kandangId tidak found: $e');
            }
          }
        }

        if (capturedTotals.isNotEmpty) {
          await NotificationService.instance.showPanenSummaryNotification(
            jenisPanen: 'sore',
            kandangTotals: capturedTotals,
          );
        }

        if (kDebugMode) {
          print('✅ Afternoon capture triggered for all kandang');
        }

        // Reset snapshot harian setelah panen sore selesai
        // Ini memastikan bahwa hasil panen sore akan otomatis direset untuk hari berikutnya
        Future.delayed(const Duration(seconds: 5), () {
          panenProvider.resetDailySnapshots();
          if (kDebugMode) {
            print(
                '🔄 Daily snapshots reset after afternoon capture (panen sore)');
          }
        });
      }
    } catch (e) {
      if (kDebugMode) {
        print('❌ Error in triggerAfternoonCapture: $e');
      }
    }
  }

  /// Initialize auto-capture service
  /// Panggil ini saat app start untuk restore state hari ini
  static Future<void> initialize(PanenProvider panenProvider) async {
    try {
      if (kDebugMode) {
        print('🚀 Initializing PanenAutoCaptureService');
      }

      // Load today's snapshots dari Firebase
      await panenProvider.loadTodaySnapshots();

      // Restore historical panen data
      await panenProvider.restorePanenHistoryFromFirebase();

      if (kDebugMode) {
        print('✅ PanenAutoCaptureService initialized');
      }
    } catch (e) {
      if (kDebugMode) {
        print('❌ Error initializing PanenAutoCaptureService: $e');
      }
    }
  }
}
