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

class TambahPemeriksaanKehamilanPage extends StatefulWidget {
  final String ibuHamilId;
  final String nama;

  const TambahPemeriksaanKehamilanPage({
    super.key,
    required this.ibuHamilId,
    required this.nama,
  });

  @override
  State<TambahPemeriksaanKehamilanPage> createState() =>
      _TambahPemeriksaanKehamilanPageState();
}

class _TambahPemeriksaanKehamilanPageState
    extends State<TambahPemeriksaanKehamilanPage> {
  final tanggalController = TextEditingController();
  final displayTanggalController = TextEditingController();

  final bbSebelumController = TextEditingController(); // Baru
  final beratController = TextEditingController();
  final tinggiController = TextEditingController(); // Baru
  final lilaController = TextEditingController(); // Baru
  final tekananController = TextEditingController();
  final fundusController = TextEditingController();
  final djjController = TextEditingController();
  final hbController = TextEditingController();
  final keluhanController = TextEditingController();
  final tindakanController = TextEditingController();

  String? kakiBengkak;
  String? statusGizi; // Baru

  final String url =
      "http://ta.myhost.id/E31230549/mposyandu_api/pemeriksaan_kehamilan/tambah_pemeriksaan_kehamilan.php";

  @override
  void initState() {
    super.initState();
    DateTime sekarang = DateTime.now();
    tanggalController.text = DateFormat('yyyy-MM-dd').format(sekarang);
    displayTanggalController.text = formatKeIndonesia(sekarang);
  }

  @override
  void dispose() {
    tanggalController.dispose();
    displayTanggalController.dispose();
    bbSebelumController.dispose();
    beratController.dispose();
    tinggiController.dispose();
    lilaController.dispose();
    tekananController.dispose();
    fundusController.dispose();
    djjController.dispose();
    hbController.dispose();
    keluhanController.dispose();
    tindakanController.dispose();
    super.dispose();
  }

  String formatKeIndonesia(DateTime date) {
    List<String> bulan = [
      "Januari",
      "Februari",
      "Maret",
      "April",
      "Mei",
      "Juni",
      "Juli",
      "Agustus",
      "September",
      "Oktober",
      "November",
      "Desember"
    ];
    return "${date.day} ${bulan[date.month - 1]} ${date.year}";
  }

  Future<void> pilihTanggal() async {
    final DateTime? picked = await showDatePicker(
      context: context,
      initialDate: DateTime.now(),
      firstDate: DateTime(2000),
      lastDate: DateTime(2100),
    );

    if (picked != null) {
      setState(() {
        tanggalController.text = DateFormat('yyyy-MM-dd').format(picked);
        displayTanggalController.text = formatKeIndonesia(picked);
      });
    }
  }

  Future<void> simpanData() async {
    if (kakiBengkak == null || statusGizi == null) {
      ScaffoldMessenger.of(context).showSnackBar(
        SnackBar(
          content: Text(
            "Silahkan lengkapi status Kaki Bengkak dan Status Gizi",
            style: GoogleFonts.poppins(fontSize: 12),
          ),
        ),
      );
      return;
    }

    try {
      final response = await http.post(
        Uri.parse(url),
        body: {
          "ibu_hamil_id": widget.ibuHamilId,
          "tanggal_pemeriksaan": tanggalController.text,
          "bb_sebelum_hamil": bbSebelumController.text,
          "berat_badan": beratController.text,
          "tinggi_badan": tinggiController.text,
          "LILA": lilaController.text,
          "status_gizi": statusGizi ?? "",
          "tekanan_darah": tekananController.text,
          "tinggi_fundus": fundusController.text,
          "denyut_jantung_janin": djjController.text,
          "hb": hbController.text,
          "kaki_bengkak": kakiBengkak ?? "",
          "keluhan": keluhanController.text,
          "tindakan": tindakanController.text,
        },
      );

      final res = jsonDecode(response.body);

      if (res["success"] == true) {
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(
            content: Text(
              "Data berhasil disimpan",
              style: GoogleFonts.poppins(fontSize: 12),
            ),
          ),
        );
        Navigator.pop(context, true);
      } else {
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(
            content: Text(
              res["message"] ?? "Gagal menyimpan data",
              style: GoogleFonts.poppins(fontSize: 12),
            ),
          ),
        );
      }
    } catch (e) {
      ScaffoldMessenger.of(context).showSnackBar(
        SnackBar(
          content: Text(
            "Terjadi kesalahan koneksi",
            style: GoogleFonts.poppins(fontSize: 12),
          ),
        ),
      );
    }
  }

  Widget input(String label, TextEditingController controller,
      {bool readOnly = false,
      VoidCallback? onTap,
      TextInputType type = TextInputType.text}) {
    return Padding(
      padding: const EdgeInsets.only(bottom: 14),
      child: Row(
        children: [
          SizedBox(
            width: 160,
            child: Text(
              label,
              style: GoogleFonts.poppins(
                  fontSize: 12, fontWeight: FontWeight.w500),
            ),
          ),
          Text(" : ", style: GoogleFonts.poppins(fontSize: 12)),
          Expanded(
            child: TextField(
              controller: controller,
              readOnly: readOnly,
              onTap: onTap,
              keyboardType: type,
              style: GoogleFonts.poppins(fontSize: 12),
              decoration: InputDecoration(
                contentPadding:
                    const EdgeInsets.symmetric(horizontal: 10, vertical: 10),
                border: OutlineInputBorder(
                  borderRadius: BorderRadius.circular(8),
                ),
              ),
            ),
          )
        ],
      ),
    );
  }

  Widget dropdownGizi() {
    return Padding(
      padding: const EdgeInsets.only(bottom: 14),
      child: Row(
        children: [
          SizedBox(
            width: 160,
            child: Text(
              "Status Gizi",
              style: GoogleFonts.poppins(
                  fontSize: 12, fontWeight: FontWeight.w500),
            ),
          ),
          Text(" : ", style: GoogleFonts.poppins(fontSize: 12)),
          Expanded(
            child: DropdownButtonFormField<String>(
              value: statusGizi,
              style: GoogleFonts.poppins(fontSize: 12, color: Colors.black),
              hint: Text("Pilih Status",
                  style: GoogleFonts.poppins(fontSize: 12)),
              items: [
                DropdownMenuItem(
                    value: "KEK (Kekurangan Energi Kronis)",
                    child:
                        Text("KEK", style: GoogleFonts.poppins(fontSize: 12))),
                DropdownMenuItem(
                    value: "Normal",
                    child: Text("Normal",
                        style: GoogleFonts.poppins(fontSize: 12))),
              ],
              onChanged: (value) => setState(() => statusGizi = value),
              decoration: InputDecoration(
                contentPadding:
                    const EdgeInsets.symmetric(horizontal: 10, vertical: 10),
                border:
                    OutlineInputBorder(borderRadius: BorderRadius.circular(8)),
              ),
            ),
          )
        ],
      ),
    );
  }

  Widget dropdownKakiBengkak() {
    return Padding(
      padding: const EdgeInsets.only(bottom: 14),
      child: Row(
        children: [
          SizedBox(
            width: 160,
            child: Text(
              "Kaki Bengkak",
              style: GoogleFonts.poppins(
                  fontSize: 12, fontWeight: FontWeight.w500),
            ),
          ),
          Text(" : ", style: GoogleFonts.poppins(fontSize: 12)),
          Expanded(
            child: DropdownButtonFormField<String>(
              value: kakiBengkak,
              style: GoogleFonts.poppins(fontSize: 12, color: Colors.black),
              hint: Text("Pilih", style: GoogleFonts.poppins(fontSize: 12)),
              items: [
                DropdownMenuItem(
                    value: "Iya",
                    child:
                        Text("Iya", style: GoogleFonts.poppins(fontSize: 12))),
                DropdownMenuItem(
                    value: "Tidak",
                    child: Text("Tidak",
                        style: GoogleFonts.poppins(fontSize: 12))),
              ],
              onChanged: (value) => setState(() => kakiBengkak = value),
              decoration: InputDecoration(
                contentPadding:
                    const EdgeInsets.symmetric(horizontal: 10, vertical: 10),
                border:
                    OutlineInputBorder(borderRadius: BorderRadius.circular(8)),
              ),
            ),
          )
        ],
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("",
            style: GoogleFonts.poppins(color: Colors.white, fontSize: 16)),
        backgroundColor: Colors.blue,
        elevation: 0,
        leading: IconButton(
          icon: const Icon(Icons.arrow_back, color: Colors.white),
          onPressed: () => Navigator.pop(context),
        ),
      ),
      body: SingleChildScrollView(
        padding: const EdgeInsets.all(16),
        child: Column(
          children: [
            Center(
              child: Text(
                "Tambah Pemeriksaan Kehamilan",
                style: GoogleFonts.poppins(
                  fontSize: 18,
                  fontWeight: FontWeight.w600,
                  color: Colors.black,
                ),
              ),
            ),
            const SizedBox(height: 16),
            Center(
              child: SizedBox(
                width: 500,
                child: Card(
                  color: Colors.white,
                  elevation: 2,
                  shape: RoundedRectangleBorder(
                    borderRadius: BorderRadius.circular(12),
                  ),
                  child: Column(
                    children: [
                      Container(
                        width: double.infinity,
                        padding: const EdgeInsets.all(14),
                        decoration: const BoxDecoration(
                          color: Colors.blue,
                          borderRadius: BorderRadius.vertical(
                            top: Radius.circular(12),
                          ),
                        ),
                        child: Text(
                          widget.nama,
                          style: GoogleFonts.poppins(
                            color: Colors.white,
                            fontWeight: FontWeight.w600,
                            fontSize: 13,
                          ),
                        ),
                      ),
                      Padding(
                        padding: const EdgeInsets.all(16),
                        child: Column(
                          children: [
                            input(
                              "Tanggal Pemeriksaan",
                              displayTanggalController,
                              readOnly: true,
                              onTap: pilihTanggal,
                            ),
                            input("BB Sebelum Hamil (kg)", bbSebelumController,
                                type: TextInputType.number),
                            input("Berat Badan Sekarang (kg)", beratController,
                                type: TextInputType.number),
                            input("Tinggi Badan (cm)", tinggiController,
                                type: TextInputType.number),
                            input("LILA (cm)", lilaController,
                                type: TextInputType.number),
                            dropdownGizi(),
                            input("Tekanan Darah", tekananController),
                            input("Tinggi Fundus (cm)", fundusController,
                                type: TextInputType.number),
                            input("Denyut Jantung Janin", djjController),
                            input("HB", hbController),
                            dropdownKakiBengkak(),
                            input("Keluhan", keluhanController),
                            input("Tindakan", tindakanController),
                            const SizedBox(height: 20),
                            Center(
                              child: SizedBox(
                                width: 200,
                                child: OutlinedButton(
                                  style: OutlinedButton.styleFrom(
                                    side: const BorderSide(
                                        color: Colors.blue, width: 2),
                                    shape: const StadiumBorder(),
                                    padding: const EdgeInsets.symmetric(
                                        vertical: 14),
                                  ),
                                  onPressed: simpanData,
                                  child: Text(
                                    "Simpan",
                                    style: GoogleFonts.poppins(
                                        color: Colors.blue,
                                        fontSize: 12,
                                        fontWeight: FontWeight.bold),
                                  ),
                                ),
                              ),
                            ),
                          ],
                        ),
                      )
                    ],
                  ),
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }
}
