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

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

  @override
  State<HomeScreen> createState() => _HomeScreenState();
}

class _HomeScreenState extends State<HomeScreen> {
  bool _isSaldoVisible = true;

  final formatRupiah = NumberFormat.currency(locale: 'id_ID', symbol: 'Rp. ');

  final uid = FirebaseAuth.instance.currentUser!.uid;

  String? _rfid; // 🔥 simpan RFID sekali saja

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

  Future<void> _loadRfid() async {
    final doc = await FirebaseFirestore.instance
        .collection('users')
        .doc(uid)
        .get();

    final data = doc.data() as Map<String, dynamic>;
    setState(() {
      _rfid = data['rfid_uid'];
    });
  }

  @override
  Widget build(BuildContext context) {
    if (_rfid == null) {
      return const Scaffold(body: Center(child: CircularProgressIndicator()));
    }

    return Scaffold(
      backgroundColor: const Color.fromARGB(255, 11, 22, 0),
      body: SingleChildScrollView(
        child: Column(
          children: [
            // ================= TOP AREA =================
            StreamBuilder<DocumentSnapshot>(
              stream: FirebaseFirestore.instance
                  .collection('users')
                  .doc(uid)
                  .snapshots(),
              builder: (context, snapshot) {
                if (!snapshot.hasData) {
                  return const SizedBox();
                }

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

                final nama = data['nama'] ?? 'No Name';
                final rfid = data['rfid_uid'] ?? '-';

                return Container(
                  padding: const EdgeInsets.fromLTRB(20, 50, 20, 25),
                  decoration: const BoxDecoration(
                    color: Color.fromARGB(255, 165, 204, 54),
                    borderRadius: BorderRadius.only(
                      bottomLeft: Radius.circular(30),
                      bottomRight: Radius.circular(30),
                    ),
                  ),
                  child: Column(
                    children: [
                      // PROFILE
                      Row(
                        mainAxisAlignment: MainAxisAlignment.spaceBetween,
                        children: [
                          GestureDetector(
                            onTap: () {
                              Navigator.push(
                                context,
                                MaterialPageRoute(
                                  builder: (context) => const AkunScreen(),
                                ),
                              );
                            },
                            child: Row(
                              children: [
                                const CircleAvatar(
                                  radius: 22,
                                  backgroundColor: Colors.black12,
                                  child: Icon(Icons.person),
                                ),
                                const SizedBox(width: 10),
                                Column(
                                  crossAxisAlignment: CrossAxisAlignment.start,
                                  children: [
                                    Text(
                                      nama,
                                      style: const TextStyle(
                                        fontWeight: FontWeight.bold,
                                      ),
                                    ),
                                    Text(
                                      rfid,
                                      style: const TextStyle(fontSize: 12),
                                    ),
                                  ],
                                ),
                              ],
                            ),
                          ),
                          Container(
                            padding: const EdgeInsets.all(8),
                            decoration: BoxDecoration(
                              color: Colors.black,
                              borderRadius: BorderRadius.circular(12),
                            ),
                            child: const Icon(
                              Icons.notifications,
                              color: Colors.white,
                            ),
                          ),
                        ],
                      ),

                      const SizedBox(height: 25),

                      // ================= SALDO (RTDB) =================
                      StreamBuilder<DatabaseEvent>(
                        stream: FirebaseDatabase.instance
                            .ref('users/$_rfid')
                            .onValue,
                        builder: (context, snapshot) {
                          if (!snapshot.hasData ||
                              snapshot.data!.snapshot.value == null) {
                            return const SizedBox();
                          }

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

                          final saldo = data['saldo'] ?? 0;

                          return Container(
                            padding: const EdgeInsets.all(20),
                            decoration: BoxDecoration(
                              color: const Color.fromARGB(255, 223, 242, 112),
                              borderRadius: BorderRadius.circular(25),
                            ),
                            child: Column(
                              crossAxisAlignment: CrossAxisAlignment.start,
                              children: [
                                const Text("Total Saldo"),
                                const SizedBox(height: 8),
                                Row(
                                  mainAxisAlignment:
                                      MainAxisAlignment.spaceBetween,
                                  children: [
                                    Text(
                                      _isSaldoVisible
                                          ? formatRupiah.format(saldo)
                                          : "Rp. ••••••",
                                      style: const TextStyle(
                                        fontSize: 28,
                                        fontWeight: FontWeight.bold,
                                      ),
                                    ),
                                    IconButton(
                                      onPressed: () {
                                        setState(() {
                                          _isSaldoVisible = !_isSaldoVisible;
                                        });
                                      },
                                      icon: Icon(
                                        _isSaldoVisible
                                            ? Icons.visibility
                                            : Icons.visibility_off,
                                      ),
                                    ),
                                  ],
                                ),
                                const SizedBox(height: 15),
                                Row(
                                  children: [
                                    GestureDetector(
                                      onTap: () {
                                        Navigator.push(
                                          context,
                                          MaterialPageRoute(
                                            builder: (_) =>
                                                SendScreen(myRfid: _rfid!),
                                          ),
                                        );
                                      },
                                      child: _actionButton(
                                        Icons.north_east,
                                        "Send",
                                      ),
                                    ),
                                    const SizedBox(width: 20),
                                  ],
                                ),
                              ],
                            ),
                          );
                        },
                      ),
                    ],
                  ),
                );
              },
            ),

            const SizedBox(height: 25),

            const SizedBox(height: 20),

            // ================= BOTOL (RTDB) =================
            StreamBuilder<DatabaseEvent>(
              stream: FirebaseDatabase.instance.ref('users/$_rfid').onValue,
              builder: (context, snapshot) {
                if (!snapshot.hasData ||
                    snapshot.data!.snapshot.value == null) {
                  return const SizedBox();
                }

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

                final plastik = data['botol_plastik'] ?? 0;
                final kaleng = data['botol_kaleng'] ?? 0;
                final kaca = data['botol_kaca'] ?? 0;

                return Container(
                  margin: const EdgeInsets.symmetric(horizontal: 20),
                  padding: const EdgeInsets.all(20),
                  decoration: BoxDecoration(
                    color: const Color.fromARGB(255, 223, 242, 112),
                    borderRadius: BorderRadius.circular(20),
                  ),
                  child: Column(
                    children: [
                      _itemBotol(
                        iconPath: "assets/plastik.png",
                        title: "Botol Plastik",
                        harga: "Rp. 500 / botol",
                        jumlah: plastik,
                      ),
                      const SizedBox(height: 15),
                      _itemBotol(
                        iconPath: "assets/kaleng.png",
                        title: "Botol Kaleng",
                        harga: "Rp. 1000 / botol",
                        jumlah: kaleng,
                      ),
                      const SizedBox(height: 15),
                      _itemBotol(
                        iconPath: "assets/kaca.png",
                        title: "Botol Kaca",
                        harga: "Rp. 2000 / botol",
                        jumlah: kaca,
                      ),
                    ],
                  ),
                );
              },
            ),

            const SizedBox(height: 40),
          ],
        ),
      ),
    );
  }

  Widget _itemBotol({
    required String iconPath,
    required String title,
    required String harga,
    required int jumlah,
  }) {
    return Row(
      mainAxisAlignment: MainAxisAlignment.spaceBetween,
      children: [
        Row(
          children: [
            Container(
              padding: const EdgeInsets.all(12),
              decoration: BoxDecoration(
                color: const Color.fromARGB(255, 165, 204, 54),
                borderRadius: BorderRadius.circular(20),
              ),
              child: Image.asset(iconPath, width: 28, height: 28),
            ),
            const SizedBox(width: 12),
            Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Text(
                  title,
                  style: const TextStyle(fontWeight: FontWeight.bold),
                ),
                Text(harga, style: const TextStyle(fontSize: 12)),
              ],
            ),
          ],
        ),
        Text(
          jumlah.toString(),
          style: const TextStyle(fontWeight: FontWeight.bold),
        ),
      ],
    );
  }

  Widget _actionButton(IconData icon, String label) {
    return Column(
      children: [
        Container(
          padding: const EdgeInsets.all(12),
          decoration: BoxDecoration(
            color: Colors.black,
            borderRadius: BorderRadius.circular(12),
          ),
          child: Icon(icon, color: Colors.white),
        ),
        const SizedBox(height: 6),
        Text(label, style: const TextStyle(fontSize: 12)),
      ],
    );
  }
}
