import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:google_fonts/google_fonts.dart';
import 'package:http/http.dart' as http;

class RiwayatPemeriksaanBalitaPage extends StatefulWidget {
  final String idBalita;
  final String namaBalita;

  const RiwayatPemeriksaanBalitaPage({
    super.key,
    required this.idBalita,
    required this.namaBalita,
  });

  @override
  State<RiwayatPemeriksaanBalitaPage> createState() =>
      _RiwayatPemeriksaanBalitaPageState();
}

class _RiwayatPemeriksaanBalitaPageState
    extends State<RiwayatPemeriksaanBalitaPage> {
  List dataRiwayat = [];
  List dataFilter = [];
  bool isLoading = true;

  final TextEditingController searchController = TextEditingController();
  final baseUrl =
      "http://ta.myhost.id/E31230549/mposyandu_api/pemeriksaan_balita_ibu";

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

  Future<void> getRiwayat() async {
    setState(() => isLoading = true);
    try {
      final response = await http.post(
        Uri.parse("$baseUrl/get_riwayat_pemeriksaan_balita.php"),
        body: {
          "id_balita": widget.idBalita,
        },
      );

      final data = json.decode(response.body);

      if (data["success"]) {
        setState(() {
          dataRiwayat = data["data"];
          dataFilter = data["data"];
          isLoading = false;
        });
      } else {
        setState(() => isLoading = false);
      }
    } catch (e) {
      debugPrint(e.toString());
      setState(() => isLoading = false);
    }
  }

  void _filterData(String keyword) {
    final key = keyword.toLowerCase();
    setState(() {
      dataFilter = dataRiwayat.where((item) {
        return item['tanggal_pemeriksaan']
                .toString()
                .toLowerCase()
                .contains(key) ||
            item['status_bbu'].toString().toLowerCase().contains(key) ||
            item['status_tbu'].toString().toLowerCase().contains(key) ||
            item['status_bbtb'].toString().toLowerCase().contains(key) ||
            item['imunisasi'].toString().toLowerCase().contains(key);
      }).toList();
    });
  }

  String formatTanggal(String? tanggal) {
    if (tanggal == null || tanggal.isEmpty) 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 Scaffold(
      backgroundColor: const Color(0xFFFDFDFD),
      appBar: AppBar(
        backgroundColor: Colors.blueAccent,
        iconTheme: const IconThemeData(color: Colors.white),
        elevation: 0,
        title: Text(
          "",
          style: GoogleFonts.poppins(color: Colors.white, fontSize: 16),
        ),
      ),
      body: isLoading
          ? const Center(child: CircularProgressIndicator())
          : Column(
              children: [
                Padding(
                  padding: const EdgeInsets.only(top: 20, bottom: 12),
                  child: Center(
                    child: Text(
                      "Riwayat Pemeriksaan",
                      style: GoogleFonts.poppins(
                        fontSize: 18,
                        fontWeight: FontWeight.w600,
                      ),
                    ),
                  ),
                ),
                Padding(
                  padding:
                      const EdgeInsets.symmetric(horizontal: 20, vertical: 10),
                  child: TextField(
                    controller: searchController,
                    onChanged: _filterData,
                    style: GoogleFonts.poppins(fontSize: 12),
                    decoration: InputDecoration(
                      hintText: "Cari tanggal atau status gizi...",
                      prefixIcon: const Icon(Icons.search,
                          size: 20, color: Colors.grey),
                      contentPadding: const EdgeInsets.symmetric(vertical: 10),
                      border: OutlineInputBorder(
                        borderRadius: BorderRadius.circular(10),
                      ),
                    ),
                  ),
                ),
                const SizedBox(height: 10),
                Expanded(
                  child: dataFilter.isEmpty
                      ? Center(
                          child: Text(
                            "Data tidak ditemukan",
                            style: GoogleFonts.poppins(
                                fontSize: 12, color: Colors.grey),
                          ),
                        )
                      : ListView.builder(
                          itemCount: dataFilter.length,
                          itemBuilder: (context, index) {
                            final balita = dataFilter[index];
                            return _cardBalita(balita);
                          },
                        ),
                ),
              ],
            ),
    );
  }

  Widget _cardBalita(Map balita) {
    return Container(
      margin: const EdgeInsets.symmetric(horizontal: 20, vertical: 8),
      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.circular(12),
        border: Border.all(color: Colors.grey.shade200),
        boxShadow: const [
          BoxShadow(color: Colors.black12, blurRadius: 5, offset: Offset(0, 2)),
        ],
      ),
      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(
              widget.namaBalita,
              style: GoogleFonts.poppins(
                color: Colors.white,
                fontSize: 13,
                fontWeight: FontWeight.w600,
              ),
            ),
          ),
          Padding(
            padding: const EdgeInsets.all(12),
            child: Column(
              children: [
                _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"),

                // --- PERUBAHAN STATUS GIZI ---
                _row("Status (BB/U)", balita["status_bbu"] ?? "-"),
                _row("Status (TB/U)", balita["status_tbu"] ?? "-"),
                _row("Status (BB/TB)", balita["status_bbtb"] ?? "-"),
                // -----------------------------

                _row("Imunisasi", balita["imunisasi"] ?? "-"),
                _row("Vitamin A", balita["vitamin_a"] ?? "-"),
                _row("PMT", balita["pmt"] ?? "-"),
                _row("Catatan", balita["catatan"] ?? "-"),
              ],
            ),
          ),
        ],
      ),
    );
  }

  Widget _row(String label, String value) {
    return Padding(
      padding: const EdgeInsets.symmetric(vertical: 2),
      child: Row(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          SizedBox(
            width: 130, // Sedikit diperkecil agar pas
            child: Text(
              label,
              style: GoogleFonts.poppins(
                  fontSize: 11, fontWeight: FontWeight.w600),
            ),
          ),
          Text(" : ",
              style: GoogleFonts.poppins(
                  fontSize: 11, fontWeight: FontWeight.bold)),
          Expanded(
            child: Text(
              value,
              style: GoogleFonts.poppins(fontSize: 11),
            ),
          ),
        ],
      ),
    );
  }
}
