import 'dart:convert';

import 'package:flutter/material.dart';

import 'package:google_fonts/google_fonts.dart';

import 'package:http/http.dart' as http;

import 'package:shared_preferences/shared_preferences.dart';

import '../layout/main_layout.dart';

import 'ibu_drawer.dart';

import '../ibu/crud_pemeriksaaan_balita/riwayat_pemeriksaan_balita.dart';

// Import Dashboard Ibu agar navigasi PopScope berfungsi

import '../ibu/dashboard_ibu.dart';

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

  @override
  State<PemeriksaanBalitaIbuPage> createState() =>
      _PemeriksaanBalitaIbuPageState();
}

class _PemeriksaanBalitaIbuPageState extends State<PemeriksaanBalitaIbuPage> {
  List dataBalita = [];

  bool isLoading = true;

  final baseUrl =
      "http://ta.myhost.id/E31230549/mposyandu_api/pemeriksaan_balita_ibu";

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

    getDataBalita();
  }

 Future<void> getDataBalita() async {
    final prefs = await SharedPreferences.getInstance();
    
    // SESUAI KODE LOGIN: Mengambil key "id_user" (bukan "idUser" atau "user_id")
    String? idUser = prefs.getString("id_user"); 

    if (idUser == null) {
      setState(() {
        isLoading = false;
      });
      return;
    }

    try {
      final response = await http.post(
        Uri.parse("$baseUrl/get_pemeriksaan_balita_ibu.php"),
        body: {
          "id_user": idUser, // Mengirim string ID ke server PHP
        },
      );

      if (response.statusCode == 200) {
        final data = json.decode(response.body);

        if (data["success"] == true) {
          setState(() {
            dataBalita = data["data"];
            isLoading = false;
          });
        } else {
          setState(() {
            isLoading = false;
          });
        }
      } else {
        setState(() {
          isLoading = false;
        });
      }
    } catch (e) {
      setState(() {
        isLoading = false;
      });
      debugPrint("Koneksi gagal atau eror data: $e");
    }
  }

  String formatTanggal(String? tanggal) {
    if (tanggal == null) return "-";

    try {
      DateTime dt = DateTime.parse(tanggal);

      const bulan = [
        "",
        "Januari",
        "Februari",
        "Maret",
        "April",
        "Mei",
        "Juni",
        "Juli",
        "Agustus",
        "September",
        "Oktober",
        "November",
        "Desember"
      ];

      return "${dt.day} ${bulan[dt.month]} ${dt.year}";
    } catch (e) {
      return "-";
    }
  }

  @override
  Widget build(BuildContext context) {
    return PopScope(
      canPop: false,
      onPopInvokedWithResult: (didPop, result) async {
        if (didPop) return;

        // ✅ FIX FINAL: selalu kembali ke Dashboard Ibu

        Navigator.pushAndRemoveUntil(
          context,
          MaterialPageRoute(
            builder: (_) => const DashboardIbuPage(),
          ),
          (route) => false,
        );
      },
      child: MainLayout(
        title: "",
        drawer: const IbuDrawer(),
        body: isLoading
            ? const Center(child: CircularProgressIndicator())
            : Padding(
                padding: const EdgeInsets.all(16),
                child: Column(
                  children: [
                    Center(
                      child: Text(
                        "Hasil Pemeriksaan",
                        style: GoogleFonts.poppins(
                          fontSize: 18,
                          fontWeight: FontWeight.w600,
                        ),
                      ),
                    ),
                    const SizedBox(height: 20),
                    Expanded(
                      child: dataBalita.isEmpty
                          ? Center(
                              child: Text(
                                "Belum ada data pemeriksaan",
                                style: GoogleFonts.poppins(fontSize: 12),
                              ),
                            )
                          : ListView.builder(
                              itemCount: dataBalita.length,
                              itemBuilder: (context, index) {
                                final balita = dataBalita[index];

                                return _cardBalita(balita);
                              },
                            ),
                    ),
                  ],
                ),
              ),
      ),
    );
  }

  Widget _cardBalita(Map balita) {
    return Container(
      margin: const EdgeInsets.only(bottom: 16),
      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.circular(12),
        boxShadow: const [
          BoxShadow(
            color: Colors.black12,
            blurRadius: 8,
            offset: Offset(0, 4),
          ),
        ],
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Container(
            width: double.infinity,
            padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 10),
            decoration: const BoxDecoration(
              color: Colors.blueAccent,
              borderRadius: BorderRadius.vertical(top: Radius.circular(12)),
            ),
            child: Text(
              balita["nama_balita"] ?? "-",
              style: GoogleFonts.poppins(
                color: Colors.white,
                fontSize: 12,
                fontWeight: FontWeight.w600,
              ),
            ),
          ),
          Padding(
            padding: const EdgeInsets.all(12),
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Text(
                  "Pemeriksaan Terakhir",
                  style: GoogleFonts.poppins(
                    fontSize: 12,
                    fontWeight: FontWeight.w600,
                  ),
                ),
                const SizedBox(height: 8),
                _row("Tanggal Posyandu",
                    formatTanggal(balita["tanggal_pemeriksaan"])),
                _row("Berat Badan", "${balita["bb"] ?? "-"} kg"),
                _row("Tinggi Badan", "${balita["tb"] ?? "-"} cm"),
                _row("Lingkar Kepala", "${balita["lk"] ?? "-"} cm"),
                _row("Status Gizi (BB/U)", balita["status_bbu"] ?? "-"),
                _row("Status Gizi (TB/U)", balita["status_tbu"] ?? "-"),
                _row("Status Gizi (BB/TB)", balita["status_bbtb"] ?? "-"),
                _row("Pemberian Imunisasi", balita["imunisasi"] ?? "-"),
                _row("Pemberian Vitamin A", balita["vitamin_a"] ?? "-"),
                _row("Pemberian PMT", balita["pmt"] ?? "-"),
                _row("Catatan Kader", balita["catatan"] ?? "-"),
                const SizedBox(height: 16),
                Center(
                  child: OutlinedButton.icon(
                    onPressed: () {
                      Navigator.push(
                        context,
                        MaterialPageRoute(
                          builder: (context) => RiwayatPemeriksaanBalitaPage(
                            idBalita: balita["id_balita"].toString(),
                            namaBalita: balita["nama_balita"] ?? "-",
                          ),
                        ),
                      );
                    },
                    icon: const Icon(Icons.history,
                        size: 14, color: Colors.blueAccent),
                    label: Text(
                      "Riwayat",
                      style: GoogleFonts.poppins(
                        fontSize: 12,
                        color: Colors.blueAccent,
                        fontWeight: FontWeight.w500,
                      ),
                    ),
                    style: OutlinedButton.styleFrom(
                      side: const BorderSide(color: Colors.blueAccent),
                      shape: RoundedRectangleBorder(
                        borderRadius: BorderRadius.circular(20),
                      ),
                      padding: const EdgeInsets.symmetric(
                          horizontal: 20, vertical: 4),
                      minimumSize: const Size(0, 34),
                    ),
                  ),
                ),
              ],
            ),
          ),
        ],
      ),
    );
  }

  Widget _row(String label, String value) {
    return Padding(
      padding: const EdgeInsets.symmetric(vertical: 2),
      child: Row(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          SizedBox(
            width: 150,
            child: Text(
              label,
              style: GoogleFonts.poppins(
                fontSize: 12,
                fontWeight: FontWeight.w600,
              ),
            ),
          ),
          SizedBox(
            width: 10,
            child: Text(
              ":",
              style: GoogleFonts.poppins(
                fontSize: 12,
                fontWeight: FontWeight.w600,
              ),
            ),
          ),
          Expanded(
            child: Text(
              value,
              style: GoogleFonts.poppins(fontSize: 12),
            ),
          ),
        ],
      ),
    );
  }
}
