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_pemeriksaan_anc/riwayat_pemeriksaan_anc.dart';
// Import Dashboard Ibu agar navigasi PopScope berfungsi
import '../ibu/dashboard_ibu.dart';

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

  @override
  State<PemeriksaanANCPage> createState() => _PemeriksaanANCPageState();
}

class _PemeriksaanANCPageState extends State<PemeriksaanANCPage> {
  final String baseUrl =
      "http://ta.myhost.id/E31230549/mposyandu_api/pemeriksaan_anc";

  Map? dataPemeriksaan;

  String namaIbu = "-";
  String ibuHamilId = "";

  bool isLoading = true;

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

  Future<void> getDataANC() async {
    final prefs = await SharedPreferences.getInstance();

    String? idUser = prefs.getString("id_user");

    if (idUser == null) return;

    try {
      final response = await http.post(
        Uri.parse("$baseUrl/get_pemeriksaan_anc_ibu.php"),
        body: {"user_id": idUser},
      );

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

      if (data["success"]) {
        setState(() {
          namaIbu = data["nama"];

          ibuHamilId = data["ibu_hamil_id"].toString();

          dataPemeriksaan = data["pemeriksaan"];

          isLoading = false;
        });
      }
    } catch (e) {
      debugPrint("ERROR ANC: $e");

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

  String formatTanggal(String? tanggal) {
    if (tanggal == null || tanggal.isEmpty || tanggal == "0000-00-00")
      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(
                  crossAxisAlignment: CrossAxisAlignment.center,
                  children: [
                    Center(
                      child: Text(
                        "Hasil Pemeriksaan",
                        textAlign: TextAlign.center,
                        style: GoogleFonts.poppins(
                          fontSize: 18,
                          fontWeight: FontWeight.w600,
                        ),
                      ),
                    ),
                    const SizedBox(height: 20),
                    Container(
                      width: double.infinity,
                      decoration: BoxDecoration(
                        color: Colors.white,
                        borderRadius: BorderRadius.circular(12),
                        boxShadow: [
                          BoxShadow(
                            color: Colors.black.withOpacity(0.08),
                            blurRadius: 10,
                            offset: const Offset(0, 4),
                          ),
                        ],
                      ),
                      child: Column(
                        children: [
                          /// HEADER
                          Container(
                            width: double.infinity,
                            padding: const EdgeInsets.symmetric(
                                vertical: 10, horizontal: 12),
                            decoration: const BoxDecoration(
                              color: Colors.blue,
                              borderRadius: BorderRadius.vertical(
                                  top: Radius.circular(12)),
                            ),
                            child: Text(
                              namaIbu,
                              style: GoogleFonts.poppins(
                                color: Colors.white,
                                fontSize: 13,
                                fontWeight: FontWeight.w600,
                              ),
                            ),
                          ),

                          /// BODY CARD
                          Padding(
                            padding: const EdgeInsets.all(12),
                            child: dataPemeriksaan == null
                                ? Text(
                                    "Belum ada pemeriksaan",
                                    style: GoogleFonts.poppins(
                                        fontSize: 12, color: Colors.grey),
                                  )
                                : Column(
                                    crossAxisAlignment:
                                        CrossAxisAlignment.start,
                                    children: [
                                      Text(
                                        "Pemeriksaan Terakhir",
                                        style: GoogleFonts.poppins(
                                            fontSize: 12,
                                            fontWeight: FontWeight.w700),
                                      ),

                                      const SizedBox(height: 8),

                                      _row(
                                          "Tanggal",
                                          formatTanggal(dataPemeriksaan?[
                                              "tanggal_pemeriksaan"])),

                                      _row("Berat Badan",
                                          "${dataPemeriksaan?["berat_badan"] ?? "-"} kg"),

                                      _row(
                                          "Tekanan Darah",
                                          dataPemeriksaan?["tekanan_darah"] ??
                                              "-"),

                                      _row("Tinggi Fundus",
                                          "${dataPemeriksaan?["tinggi_fundus"] ?? "-"} cm"),

                                      _row(
                                          "DJJ",
                                          dataPemeriksaan?[
                                                  "denyut_jantung_janin"] ??
                                              "-"),

                                      _row("HB", dataPemeriksaan?["hb"] ?? "-"),

                                      _row(
                                          "Kaki Bengkak",
                                          dataPemeriksaan?["kaki_bengkak"] ??
                                              "-"),

                                      _row("Keluhan",
                                          dataPemeriksaan?["keluhan"] ?? "-"),

                                      _row("Tindak Lanjut",
                                          dataPemeriksaan?["tindakan"] ?? "-"),

                                      const SizedBox(height: 20),

                                      /// BUTTON RIWAYAT
                                      Center(
                                        child: OutlinedButton.icon(
                                          onPressed: ibuHamilId.isEmpty
                                              ? null
                                              : () {
                                                  Navigator.push(
                                                    context,
                                                    MaterialPageRoute(
                                                      builder: (_) =>
                                                          RiwayatPemeriksaanAncPage(
                                                        ibuHamilId: ibuHamilId,
                                                        nama: namaIbu,
                                                      ),
                                                    ),
                                                  );
                                                },
                                          icon: const Icon(Icons.history,
                                              size: 14, color: Colors.blue),
                                          label: Text(
                                            "Riwayat",
                                            style: GoogleFonts.poppins(
                                              fontSize: 12,
                                              fontWeight: FontWeight.w600,
                                              color: Colors.blue,
                                            ),
                                          ),
                                          style: OutlinedButton.styleFrom(
                                            side: const BorderSide(
                                                color: Colors.blue, width: 1.5),
                                            padding: const EdgeInsets.symmetric(
                                                horizontal: 20, vertical: 8),
                                            shape: RoundedRectangleBorder(
                                              borderRadius:
                                                  BorderRadius.circular(25),
                                            ),
                                          ),
                                        ),
                                      ),
                                    ],
                                  ),
                          ),
                        ],
                      ),
                    ),
                  ],
                ),
              ),
      ),
    );
  }

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