import 'package:flutter/material.dart';
import 'package:firebase_database/firebase_database.dart';
import 'package:firebase_core/firebase_core.dart';
import 'package:intl/intl.dart';

class NotifikasiPage extends StatefulWidget {
  const NotifikasiPage({super.key});

  @override
  State<NotifikasiPage> createState() => _NotifikasiPageState();
}

class _NotifikasiPageState extends State<NotifikasiPage> {
  late final DatabaseReference _riwayatRef;

  @override
  void initState() {
    super.initState();

    _riwayatRef = FirebaseDatabase.instanceFor(
      app: Firebase.app(),
      databaseURL:
          "https://tugas-akhir-9947b-default-rtdb.asia-southeast1.firebasedatabase.app",
    ).ref("Kebun/Riwayat");

    // 1. Lewati data riwayat lama saat aplikasi baru dibuka agar HP tidak spam bunyi

    // 2. LISTEN DATA REAL-TIME: Pemicu spanduk saat Python berhasil input data burung ke Firebase
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.white,
      appBar: AppBar(
        title: const Text(
          "Notifikasi",
          style: TextStyle(color: Colors.white, fontWeight: FontWeight.bold),
        ),
        centerTitle: false,
        backgroundColor: const Color(0xFF6FCF97),
        elevation: 0,
      ),
      body: StreamBuilder<DatabaseEvent>(
        stream: _riwayatRef.onValue,
        builder: (context, snapshot) {
          if (snapshot.hasError) {
            return Center(
              child: Text(
                "Terjadi error:\n${snapshot.error}",
                textAlign: TextAlign.center,
              ),
            );
          }

          if (snapshot.connectionState == ConnectionState.waiting) {
            return const Center(child: CircularProgressIndicator());
          }

          if (!snapshot.hasData || snapshot.data!.snapshot.value == null) {
            return const Center(
              child: Text(
                "Belum ada riwayat deteksi",
                style: TextStyle(fontSize: 16),
              ),
            );
          }

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

          List<Map<dynamic, dynamic>> items = [];
          data.forEach((key, value) {
            if (value is Map) {
              items.add(Map<dynamic, dynamic>.from(value));
            }
          });

          items.sort((a, b) {
            final wa = a['waktu']?.toString() ?? '';
            final wb = b['waktu']?.toString() ?? '';
            return wb.compareTo(wa);
          });

          return ListView.builder(
            padding: const EdgeInsets.all(16),
            itemCount: items.length,
            itemBuilder: (context, index) {
              final item = items[index];

              String waktu = "-";
              try {
                if (item['waktu'] != null) {
                  DateTime dt = DateTime.parse(item['waktu'].toString());
                  waktu = DateFormat('dd-MM-yyyy HH:mm:ss').format(dt);
                }
              } catch (e) {
                waktu = item['waktu']?.toString() ?? "-";
              }

              int db = 0;
              if (item['db'] != null) {
                db = double.parse(item['db'].toString()).round();
              }

              int jarak = 0;
              if (item['jarak'] != null) {
                jarak = double.parse(item['jarak'].toString()).round();
              }

              String status = item['status']?.toString() ?? "Burung Terdeteksi";
              int pir1 = int.tryParse(item['pir1']?.toString() ?? "0") ?? 0;
              int pir2 = int.tryParse(item['pir2']?.toString() ?? "0") ?? 0;

              return _itemNotif(
                title: "⚠️ $status",
                waktu: waktu,
                db: db,
                jarak: jarak,
                pir1: pir1,
                pir2: pir2,
              );
            },
          );
        },
      ),
    );
  }

  Widget _itemNotif({
    required String title,
    required String waktu,
    required int db,
    required int jarak,
    required int pir1,
    required int pir2,
  }) {
    return Container(
      margin: const EdgeInsets.only(bottom: 14),
      padding: const EdgeInsets.all(16),
      decoration: BoxDecoration(
        color: const Color(0xFFE8F5E9),
        borderRadius: BorderRadius.circular(14),
        boxShadow: [
          BoxShadow(
            color: Colors.grey.withOpacity(0.15),
            blurRadius: 6,
            offset: const Offset(0, 3),
          ),
        ],
      ),
      child: Row(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Icon(Icons.warning_amber_rounded, color: Colors.red[400], size: 40),
          const SizedBox(width: 14),
          Expanded(
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Text(
                  title,
                  style: const TextStyle(
                    fontSize: 16,
                    fontWeight: FontWeight.bold,
                  ),
                ),
                const SizedBox(height: 10),
                Text(
                  "🕒 Waktu : $waktu",
                  style: TextStyle(color: Colors.grey[700], fontSize: 14),
                ),
                const SizedBox(height: 4),
                Text(
                  "🔊 Suara : $db dB",
                  style: TextStyle(color: Colors.grey[700], fontSize: 14),
                ),
                const SizedBox(height: 4),
                Text(
                  "🚶 PIR 1 : ${pir1 == 1 ? "Aktif" : "Tidak Aktif"}",
                  style: TextStyle(color: Colors.grey[700], fontSize: 14),
                ),
                const SizedBox(height: 4),
                Text(
                  "🚶 PIR 2 : ${pir2 == 1 ? "Aktif" : "Tidak Aktif"}",
                  style: TextStyle(color: Colors.grey[700], fontSize: 14),
                ),
                const SizedBox(height: 4),
                Text(
                  "📏 Jarak : $jarak cm",
                  style: TextStyle(color: Colors.grey[700], fontSize: 14),
                ),
              ],
            ),
          ),
        ],
      ),
    );
  }
}
