import 'package:flutter/material.dart';
import 'package:firebase_auth/firebase_auth.dart';
import 'package:firebase_database/firebase_database.dart';
import 'package:cloud_firestore/cloud_firestore.dart';

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

  @override
  State<HistoryScreen> createState() => _HistoryScreenState();
}

class _HistoryScreenState extends State<HistoryScreen> {
  String? rfidUid;
  bool loading = true;

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

  Future<void> loadRFID() async {
    try {
      final firebaseUid = FirebaseAuth.instance.currentUser!.uid;

      final doc = await FirebaseFirestore.instance
          .collection('users')
          .doc(firebaseUid)
          .get();

      if (!doc.exists) {
        setState(() {
          loading = false;
        });
        return;
      }

      rfidUid = doc.data()?['rfid_uid'];

      setState(() {
        loading = false;
      });
    } catch (e) {
      debugPrint(e.toString());

      setState(() {
        loading = false;
      });
    }
  }

  @override
  Widget build(BuildContext context) {
    if (loading) {
      return const Scaffold(
        backgroundColor: Color.fromARGB(255, 11, 22, 0),
        body: Center(child: CircularProgressIndicator()),
      );
    }

    if (rfidUid == null || rfidUid!.isEmpty) {
      return const Scaffold(
        backgroundColor: Color.fromARGB(255, 11, 22, 0),
        body: Center(
          child: Text(
            "RFID UID tidak ditemukan",
            style: TextStyle(color: Colors.white),
          ),
        ),
      );
    }

    final historyRef = FirebaseDatabase.instance.ref("users/$rfidUid/history");

    return Scaffold(
      backgroundColor: const Color.fromARGB(255, 11, 22, 0),

      appBar: AppBar(
        backgroundColor: const Color.fromARGB(255, 165, 204, 54),
        centerTitle: true,
        elevation: 0,
        title: const Text(
          "Riwayat Transaksi",
          style: TextStyle(fontWeight: FontWeight.bold, color: Colors.black),
        ),
        iconTheme: const IconThemeData(color: Colors.black),
      ),

      body: StreamBuilder<DatabaseEvent>(
        stream: historyRef.onValue,
        builder: (context, snapshot) {
          if (snapshot.hasError) {
            return const Center(
              child: Text(
                "Gagal memuat data",
                style: TextStyle(color: Colors.white),
              ),
            );
          }

          if (!snapshot.hasData || snapshot.data!.snapshot.value == null) {
            return Center(
              child: Column(
                mainAxisAlignment: MainAxisAlignment.center,
                children: const [
                  Icon(Icons.receipt_long, size: 70, color: Colors.white54),
                  SizedBox(height: 10),
                  Text(
                    "Belum ada riwayat transaksi",
                    style: TextStyle(color: Colors.white70, fontSize: 16),
                  ),
                ],
              ),
            );
          }

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

          final items = data.entries.toList();

          items.sort((a, b) {
            final aData = Map<dynamic, dynamic>.from(a.value);

            final bData = Map<dynamic, dynamic>.from(b.value);

            final aWaktu = aData['waktu']?.toString() ?? '';

            final bWaktu = bData['waktu']?.toString() ?? '';

            return bWaktu.compareTo(aWaktu);
          });

          return ListView.builder(
            padding: EdgeInsets.fromLTRB(
              0,
              12,
              0,
              MediaQuery.of(context).padding.bottom + 100,
            ),
            itemCount: items.length,
            itemBuilder: (context, index) {
              final item = Map<dynamic, dynamic>.from(items[index].value);

              final String type =
                  item['type']?.toString() ?? item['jenis']?.toString() ?? '-';

              final int nilai =
                  int.tryParse(
                    (item['nilai'] ?? item['nominal'] ?? 0).toString(),
                  ) ??
                  0;

              final String waktu =
                  item['waktu']?.toString() ??
                  item['tanggal']?.toString() ??
                  '-';

              final bool isPengurangan =
                  type == "Pembayaran QRIS" || type == "transfer_keluar";

              IconData icon = Icons.recycling;

              String namaBotol = "TRANSAKSI";

              if (type == "plastik") {
                icon = Icons.local_drink;
                namaBotol = "BOTOL PLASTIK";
              } else if (type == "kaleng") {
                icon = Icons.sports_bar;
                namaBotol = "BOTOL KALENG";
              } else if (type == "kaca") {
                icon = Icons.wine_bar;
                namaBotol = "BOTOL KACA";
              } else if (type == "transfer_keluar") {
                icon = Icons.north_east;
                namaBotol = "TRANSFER KELUAR";
              } else if (type == "transfer_masuk") {
                icon = Icons.south_west;
                namaBotol = "TRANSFER MASUK";
              } else if (type == "Pembayaran QRIS") {
                icon = Icons.qr_code_scanner;
                namaBotol = "PEMBAYARAN QRIS";
              }

              return Container(
                margin: const EdgeInsets.symmetric(horizontal: 20, vertical: 6),
                padding: const EdgeInsets.all(16),
                decoration: BoxDecoration(
                  color: const Color.fromARGB(255, 223, 242, 112),
                  borderRadius: BorderRadius.circular(20),
                ),
                child: Row(
                  children: [
                    Container(
                      padding: const EdgeInsets.all(12),
                      decoration: BoxDecoration(
                        color: const Color.fromARGB(255, 165, 204, 54),
                        borderRadius: BorderRadius.circular(15),
                      ),
                      child: Icon(icon, size: 28, color: Colors.black),
                    ),

                    const SizedBox(width: 15),

                    Expanded(
                      child: Column(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: [
                          Text(
                            namaBotol,
                            style: const TextStyle(
                              fontSize: 16,
                              fontWeight: FontWeight.bold,
                            ),
                          ),

                          const SizedBox(height: 4),

                          Text(
                            isPengurangan ? "- Rp $nilai" : "+ Rp $nilai",
                            style: TextStyle(
                              fontSize: 13,
                              fontWeight: FontWeight.bold,
                              color: isPengurangan ? Colors.red : Colors.green,
                            ),
                          ),

                          if (type == "transfer_keluar")
                            Padding(
                              padding: const EdgeInsets.only(top: 3),
                              child: Text(
                                "Ke: ${item['tujuan'] ?? '-'}",
                                style: const TextStyle(
                                  fontSize: 11,
                                  color: Colors.black54,
                                ),
                              ),
                            ),

                          if (type == "transfer_masuk")
                            Padding(
                              padding: const EdgeInsets.only(top: 3),
                              child: Text(
                                "Dari: ${item['dari'] ?? '-'}",
                                style: const TextStyle(
                                  fontSize: 11,
                                  color: Colors.black54,
                                ),
                              ),
                            ),
                        ],
                      ),
                    ),

                    SizedBox(
                      width: 95,
                      child: Text(
                        waktu,
                        textAlign: TextAlign.right,
                        style: const TextStyle(
                          fontSize: 11,
                          color: Colors.black54,
                        ),
                      ),
                    ),
                  ],
                ),
              );
            },
          );
        },
      ),
    );
  }
}
