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 EditPemeriksaanKehamilanPage extends StatefulWidget {
  final Map data;
  final String nama;

  const EditPemeriksaanKehamilanPage({
    super.key,
    required this.data,
    required this.nama,
  });

  @override
  State<EditPemeriksaanKehamilanPage> createState() =>
      _EditPemeriksaanKehamilanPageState();
}

class _EditPemeriksaanKehamilanPageState
    extends State<EditPemeriksaanKehamilanPage> {
  final tanggalController = TextEditingController();
  final displayTanggalController = TextEditingController();

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

  String? kakiBengkak;
  String? statusGizi;

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

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

    tanggalController.text = widget.data["tanggal_pemeriksaan"] ?? "";

    DateTime date = DateTime.parse(
        widget.data["tanggal_pemeriksaan"] ?? DateTime.now().toString());

    displayTanggalController.text = formatKeIndonesia(date);

    bbSebelumController.text = widget.data["bb_sebelum_hamil"] ?? "";
    beratController.text = widget.data["berat_badan"] ?? "";
    tinggiController.text = widget.data["tinggi_badan"] ?? "";
    lilaController.text = widget.data["LILA"] ?? "";
    tekananController.text = widget.data["tekanan_darah"] ?? "";
    fundusController.text = widget.data["tinggi_fundus"] ?? "";
    djjController.text = widget.data["denyut_jantung_janin"] ?? "";
    hbController.text = widget.data["hb"] ?? "";
    keluhanController.text = widget.data["keluhan"] ?? "";
    tindakanController.text = widget.data["tindakan"] ?? "";

    kakiBengkak = widget.data["kaki_bengkak"];
    statusGizi = widget.data["status_gizi"];
  }

  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.parse(tanggalController.text),
      firstDate: DateTime(2000),
      lastDate: DateTime(2100),
    );

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

  Future<void> updateData() async {
    try {
      final response = await http.post(
        Uri.parse(url),
        body: {
          "id": widget.data["id"].toString(),
          "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) {
        if (!mounted) return;
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(
              backgroundColor: Colors.green,
              content: Text("Data berhasil diupdate",
                  style: GoogleFonts.poppins(color: Colors.white))),
        );
        Navigator.pop(context, true);
      }
    } catch (e) {
      debugPrint(e.toString());
    }
  }

  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()),
          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 dropdownStatusGizi() {
    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()),
          Expanded(
            child: DropdownButtonFormField<String>(
              value: statusGizi,
              style: GoogleFonts.poppins(fontSize: 12, color: Colors.black),
              items: [
                DropdownMenuItem(
                    value: "KEK (Kekurangan Energi Kronis)",
                    child: Text("KEK", style: GoogleFonts.poppins())),
                DropdownMenuItem(
                    value: "Normal",
                    child: Text("Normal", style: GoogleFonts.poppins())),
              ],
              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()),
          Expanded(
            child: DropdownButtonFormField<String>(
              value: kakiBengkak,
              style: GoogleFonts.poppins(fontSize: 12, color: Colors.black),
              items: [
                DropdownMenuItem(
                    value: "Iya",
                    child: Text("Iya", style: GoogleFonts.poppins())),
                DropdownMenuItem(
                    value: "Tidak",
                    child: Text("Tidak", style: GoogleFonts.poppins())),
              ],
              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(
      backgroundColor: Colors.white,
      appBar: AppBar(
        elevation: 0,
        backgroundColor: Colors.blue,
        leading: IconButton(
          icon: const Icon(Icons.arrow_back, color: Colors.white),
          onPressed: () => Navigator.pop(context),
        ),
        title: Text("",
            style: GoogleFonts.poppins(
                color: Colors.white,
                fontSize: 16,
                fontWeight: FontWeight.w600)),
      ),
      body: SingleChildScrollView(
        padding: const EdgeInsets.all(16),
        child: Column(
          children: [
            Center(
              child: Text(
                "Edit Pemeriksaan Kehamilan",
                style: GoogleFonts.poppins(
                    fontSize: 18, fontWeight: FontWeight.w600),
              ),
            ),
            const SizedBox(height: 16),

            /// CARD
            Center(
              child: Container(
                constraints: const BoxConstraints(maxWidth: 500),
                child: Card(
                  color: Colors.white,
                  elevation: 4,
                  clipBehavior: Clip.antiAlias,
                  shape: RoundedRectangleBorder(
                    borderRadius: BorderRadius.circular(16),
                  ),
                  child: Column(
                    children: [
                      /// HEADER BIRU
                      Container(
                        width: double.infinity,
                        padding: const EdgeInsets.all(14),
                        decoration: const BoxDecoration(
                          color: Colors.blue,
                          borderRadius: BorderRadius.vertical(
                            top: Radius.circular(16),
                          ),
                        ),
                        child: Text(
                          widget.nama,
                          style: GoogleFonts.poppins(
                              color: Colors.white, fontWeight: FontWeight.w600),
                        ),
                      ),

                      /// ISI FORM
                      Padding(
                        padding: const EdgeInsets.all(16),
                        child: Column(
                          children: [
                            input(
                                "Tanggal Pemeriksaan", displayTanggalController,
                                readOnly: true, onTap: pilihTanggal),
                            input("BB Sblm Hamil (kg)", bbSebelumController,
                                type: TextInputType.number),
                            input("Berat Badan (kg)", beratController,
                                type: TextInputType.number),
                            input("Tinggi Badan (cm)", tinggiController,
                                type: TextInputType.number),
                            input("LILA (cm)", lilaController,
                                type: TextInputType.number),
                            dropdownStatusGizi(),
                            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),

                            // --- TOMBOL SIMPAN PERUBAHAN (OUTLINED STADIUM) ---
                            SizedBox(
                              width: double.infinity,
                              child: OutlinedButton(
                                onPressed: updateData,
                                style: OutlinedButton.styleFrom(
                                  side: const BorderSide(
                                      color: Colors.blue, width: 2),
                                  shape: const StadiumBorder(),
                                  padding:
                                      const EdgeInsets.symmetric(vertical: 15),
                                ),
                                child: Text(
                                  "Simpan Perubahan",
                                  style: GoogleFonts.poppins(
                                    fontSize: 12,
                                    color: Colors.blue,
                                    fontWeight: FontWeight.bold,
                                  ),
                                ),
                              ),
                            )
                          ],
                        ),
                      )
                    ],
                  ),
                ),
              ),
            )
          ],
        ),
      ),
    );
  }
}
